发送后无法设置标题。虽然调用create(data,cb)

发送后无法设置标题。虽然调用create(data,cb)

问题描述:

我是新来的节点,并试图在mongodb中创建模型。当我打电话localhost:3000/a。我看到的请求两次在控制台也越来越误差不能设置头发送之后发送后无法设置标题。虽然调用create(data,cb)

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 = "[email protected]"; 
 
    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

+0

错误:发送之后无法设置头。意味着您尝试多次发送该响应。你可以为你的'cb'显示代码。 – Subburaj

+0

那我想弄明白我在哪里发送回应第二次。第二为什么上面的代码块运行两次? – tecx20

当您完成您的请求发生错误和然后稍后尝试发送更多相同的请求。这通常发生在有人在异步处理中犯了错误,这会在请求对象上发送事件的时间。

我看到你的代码有两个问题。首先,您尝试从路由处理程序调用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 = "[email protected]"; 
    User.create(user,function() { 
     res.send("hey"); 
    }); 
    }); 
+0

谢谢你的诀窍:D – tecx20