0

我学习 ExpressJS,但 next() 不起作用。请帮忙。

我正在观看有关 Express JS 的 Udemy 课程。我像讲师的代码一样编码,但我得到了这样的错误。

expressJS 版本:4.17.1

index.js:

const express = require("express");
const app = express();
const port = 1014;

app.use("/", (req, res, next) => {
     res.send("<h1>Home page</h1>");
     console.log("/ Ok");
     next();
});

app.use("/about", (req, res, next) => {
    res.send("<h1>About page</h1>");
    console.log("/about ok");
});


app.listen(port, () => console.log("Sunucu Aktif!: http://localhost:" + port + "/"));

当我进入 /about 页面时出现此错误。

[nodemon] restarting due to changes...
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
Sunucu Aktif!: http://localhost:1014/
/ Ok
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:526:11)
    at ServerResponse.header (C:\projects\expresslesson\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (C:\projects\expresslesson\node_modules\express\lib\response.js:170:12)
    at C:\projects\expresslesson\index.js:12:9
    at Layer.handle [as handle_request] (C:\projects\expresslesson\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\projects\expresslesson\node_modules\express\lib\router\index.js:317:13)
    at C:\projects\expresslesson\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\projects\expresslesson\node_modules\express\lib\router\index.js:335:12)
    at next (C:\projects\expresslesson\node_modules\express\lib\router\index.js:275:10)
    at C:\projects\expresslesson\index.js:8:6
/ Ok

您认为代码中的问题和解决方案是什么,我正在等待您的回复。

4

2 回答 2

0

Cannot set headers after they are sent to the client错误是因为您在调用路由处理程序next()后立即调用。您正在结束请求,因此您不应立即致电。仅在您尝试将控制权传递给下一个中间件功能时使用。res.send()/res.send()next()next

app.use('/', (req, res, next) => {
  console.log('I will pass control to the next middleware/handler.')
  next()
})

app.get('/', (req, res, next) => {
  res.send("<h1>Home</h1>")
})

此外,app.use用于在指定路径上挂载特定的中间件功能,就像上面的示例一样。

您需要做的是app.get正确处理您的路线。

const express = require("express");
const app = express();
const port = 1014;

app.use("/", (req, res, next) => {
  // will only get triggered if you access `home`
  console.log(`HelloWorld`);
  next();
});

app.get("/", (req, res, next) => {
  res.send("<h1>Home</h1>");
});

app.get("/about", (req, res, next) => {
  res.send("<h1>About page</h1>");
});

app.listen(port, () => console.log(`Listening on port ${port}`));

现在,您应该可以同时访问这两个http://localhost:1014/并且http://localhost:1014/about没有问题。

于 2020-03-01T11:42:17.533 回答
0

TLDR

正如@goto 所述,调用res.send()后不应紧跟next().

更长

视为res.send服务器输出回请求者。调用后next,您告诉 Express 将请求转发到下一个中​​间件,从技术上讲,它就是错误中间件。

在 Express 中,当请求到来时,它会查找与 URL 和方法匹配的中间件。如果没有找到,则转发到下一个中​​间件。最后一个是错误中间件,错误被抛出给用户。

于 2020-03-01T11:20:44.817 回答