2016-01-04 57 views
0

當我發佈表單時,控制檯上出現500錯誤,說:POST/items/sprinkler 500 angular.js:10766插入數據後的Mongoose 500錯誤

在我的節點控制檯中,錯誤顯示爲:Error: Failed to lookup view "error" in views directory

但我能夠將數據插入到我的數據庫。之後,這不會運行 - exec(function(err, item)。我如何解決這個問題?

mainapp /路由/ items.js

router.post('/sprinkler', function(req, res) { 
    Item.create(req.body).exec(function(err, item) { 
     console.log("printed") 
     res.json(item) 
    }); 
}); 

我的錯誤處理程序看起來像這樣(從快車本身):

if (app.get('env') === 'development') { 
    app.use(function(err, req, res, next) { 
    res.status(err.status || 500); 
    console.log("message from error handler:") 
    res.render('error', { 
     message: err.message, 
     error: err 
    }); 
    }); 
} 
+1

您的服務器正在試圖呈現一個錯誤頁面(因爲可能在您的處理程序導致錯誤,也許是一個驗證問題?),但它不能因爲缺少錯誤模板。您應該修復Express應用程序的錯誤處理程序,或者將其刪除,以便它會使服務器出現實際錯誤。 – robertklep

+0

我試着寫這個'if(err)console.log(err); (500); } else { console.log(saved); res.send(saved); '但是它顯示相同。另外我在我的views/500中添加了一個錯誤頁面,但它又顯示了相同的錯誤。 – Deke

+0

該錯誤發生_before_該代碼。我在談論全球Express錯誤處理程序,記錄在這裏(http://expressjs.com/en/guide/error-handling.html)。 – robertklep

回答

1

最終,錯誤是由這個原因引起:

Item.create(req.body).exec(...) 

.create()返回承諾,.exec()不是承諾的有效方法。

爲了解決這個問題,你有兩個選擇:

// Use a callback 
Item.create(req.body, function(err, item) { ... }); 

// Use the returned promise 
Item.create(req.body).then(function(item) { ... }, function(err) { ... }); 

然而,這留下的問題與錯誤處理程序無法正常工作,因爲缺少模板(也即一直在努力,你就可能已經得到了指向.exec不是函數的錯誤)。

而不是一個模板,你可以記錄錯誤,或者返回它的JSON(或兩者):

if (app.get('env') === 'development') { 
    app.use(function(err, req, res, next) { 
    res.status(err.status || 500); 
    console.error(err.stack); 
    res.json({ 
     message : err.message, 
     error : err 
    }); 
    }); 
} 
+0

你100%正確。而已。我使用了回調函數'Item.create(req.body,function(err,item){...});'。我也可以在前端獲取數據。我在做res.send(錯誤處理部分),但是當我啓動服務器時,它會因錯誤而關閉。你的方法是完美的。謝謝你也教我錯誤處理。 – Deke