2016-01-13 51 views
0

我是新來的節點,並試圖在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

回答

1

當您完成您的請求發生錯誤和然後稍後嘗試發送更多相同的請求。這通常發生在有人在異步處理中犯了錯誤,這會在請求對象上發送事件的時間。

我看到你的代碼有兩個問題。首先,您嘗試從路由處理程序調用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

相關問題