gpt4 book ai didi

javascript - 发送后无法设置 header 。调用 create(data,cb) 时

转载 作者:行者123 更新时间:2023-12-03 07:56:54 25 4
gpt4 key购买 nike

我是 Node 新手,正在尝试在 mongodb 中创建模型。当我调用 localhost:3000/a 时。我在控制台中两次看到请求也收到错误 Can't set headers after they are sent

module.exports = function(app) {
app.get('/',function(req,res){
res.render("adminpanel/panel",{});
});
app.get('/a',function (req,res,cb) {
console.log(req.url)
var User = app.models.test;
var user = app.models.test();
user.username = "admin";
user.type = "hey";
user.password = "132";
user.email = "admin@test.com";
User.create(user,cb);
res.send("hey");
});
};
输出:
output: 
/a
/a
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at ServerResponse.header (E:\workspace\orderapp\node_modules\express \lib\response.js:718:10)
at ServerResponse.contentType (E:\workspace\orderapp\node_modules\express\lib\response.js:551:15)
at ServerResponse.send (E:\workspace\orderapp\node_modules\express\lib\response.js:138:14)
at E:\workspace\orderapp\server\boot\root.js:14:9
at Layer.handle [as handle_request] (E:\workspace\orderapp\node_modules\express\lib\router\layer.js:95:5)
at next (E:\workspace\orderapp\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (E:\workspace\orderapp\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (E:\workspace\orderapp\node_modules\express\lib\router\layer.js:95:5)
at E:\workspace\orderapp\node_modules\express\lib\router\index.js:277:22

最佳答案

当您完成请求,然后尝试针对同一请求发送更多内容时,就会发生错误。当有人在异步处理中犯了错误,导致请求对象上发送内容的时间发生错误时,通常会发生这种情况。

我发现您的代码存在两个问题。首先,您尝试从路由处理程序调用 next() ,就好像您尚未真正完成处理请求一样。其次,您在调用 next() 之前发送 res.send(),因为 User.create() 是异步的并且会完成稍后。

我建议你使用这个:

  app.get('/a',function (req,res) {
console.log(req.url)
var User = app.models.test;
var user = app.models.test();
user.username = "admin";
user.type = "hey";
user.password = "132";
user.email = "admin@test.com";
User.create(user,function() {
res.send("hey");
});
});

关于javascript - 发送后无法设置 header 。调用 create(data,cb) 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34759448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com