【问题标题】:express get root event does not work快速获取根事件不起作用
【发布时间】:2015-08-07 15:55:08
【问题描述】:

当我请求 localhost:8080/chat?k=1&d=1 时,它会将“CHAT PAGE”写入控制台并正常工作。但是当我尝试获取 localhost:8080 时,根事件不会写入“INDEX PAGE”并且即使我将 index 设置为 false,它也会自动获取 index.html。这是我的代码;

var path = require('path');
var express = require('express');

var encData;
var appointmentKey;
var urlGetDataAreValid = false;

var app = express();

app.use(express.static(path.join(__dirname, 'static'), { index: false }));

app.get('/', function(req, res, next) {
    console.log("INDEX PAGE");
    res.sendFile('static/error.html');
});

app.get('/chat', function(req, res, next) {
    console.log("CHAT PAGE");
    encData = req.param('d');
    appointmentKey = req.param('k');

    if ((encData === undefined || encData === null) || (appointmentKey === undefined || appointmentKey === null) ) {
        res.sendfile('static/error.html');
    }
    else {
        urlGetDataAreValid = true;
        res.sendfile('static/index.html');
    }
});

var server = app.listen('8080');

【问题讨论】:

  • 您的代码对我有用,但它在第 14 行的 res.sendFile 处显示错误:TypeError: path must be absolute or specify root to res.sendFile
  • 您应该使用req.params.dreq.params.k 而不是req.param('d')req.param('k')res.sendfile 已弃用,您应该使用 res.sendFile
  • @maxkl 它不会给我错误。它只显示“index.html”。
  • 您使用的是哪个版本的 express?

标签: javascript node.js http express url-routing


【解决方案1】:

您的 express 版本似乎已过时。您必须将其更新到最新版本。在控制台中执行此命令:

npm install express@latest

您还必须将res.sendfile("static/error.html") 更改为res.sendFile(path.join(__dirname, "static/error.html")) 并将req.param("d") 更改为req.params.d

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多