![](/img/trans.png)
[英]Express app error: [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
[英]next() is not working on Express 4, Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
我学习 ExpressJS 但 next() 不起作用。 请帮忙。
我正在观看有关 Express JS 的 Udemy 课程。 我像导师的代码一样编码,但我得到了这样的错误。
expressJS 版本:4.17.1
索引.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
您认为代码中的问题和解决方案是什么,我等待您的回复。
正如@goto 所述,调用res.send()
不应紧跟next()
。
请参阅res.send
作为服务器输出回请求者。 调用next
,您是在告诉 Express 将请求转发到下一个中间件,这在技术上是错误中间件。
在 Express 中,当请求到来时,它会查找与 URL 和方法匹配的中间件。 如果没有找到,则将其转发到下一个中间件。 最后一个是错误中间件,错误被抛出给用户。
将Cannot set headers after they are sent to the client
错误是因为您在/
路由处理程序中调用res.send()
后立即调用next()
。 你用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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.