![](/img/trans.png)
[英]node.js express - handling routes as app.get('route', folder.file)
[英]'missing routes' error handling in node.js express app (failing)
我只是想在我的app.js
或路由器文件中工作來處理可能丟失的路由器錯誤。 (類似的 stackoverflow 解決方案對我不起作用)
因此,我的app.js
或路由器文件是(按原樣工作正常;但我正在嘗試正確處理丟失的路由器錯誤) :
'use strict'
var path = require('path');
var film = require('./healthymeals.js');
var express = require('express');
var router = express.Router();
var app = express();
module.exports = function(app) {
app.get('/allMeals', film.getAllMeals);
app.get('/meals/:id', film.getMealInfo);
app.get('/meals/:id/options',meal.getHealthyMealoptions);
app.get('*', function(req, res) {
res.send("Healthy meals");
});
我已經安裝了 npm 的/express 錯誤處理包 ' http-status-codes ' 。
並嘗試了它的實現:
var HttpStatus = require('http-status-codes');
response
.status(HttpStatus.OK)
.send('ok');
response
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.send({
error: HttpStatus.getStatusText(HttpStatus.INTERNAL_SERVER_ERROR)
});
當上面運行時; 我在“ response
”字上拋出的終端中出現構建錯誤。 安裝相關的 npm 包時我沒有錯誤。
ReferenceError: response is not defined
然后我嘗試了一些我在 stackover 上找到的建議,即。
function getAllApps(request, response) {
appService.getApps(request.query.$expand).then(function (apps) {
response.status(200).send(apps);
})
.catch(function (err) {
console.error('Error occurred in Apps Api: ' + err);
response.status(500).send("" + err);
});
}
這是無效的,似乎只是被忽略了。 任何指針表示贊賞(第一次使用此堆棧) 。 干杯
更新,以下來自 Jonas w 的回答 - 我第一次收到超時錯誤如下:
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
然后在增加超時后,我收到以下錯誤:
TypeError: Cannot read property 'status' of undefined
有關更多上下文,這是我的嘗試未通過的測試:
describe('error handling', function() {
it('handles missing routes', function(done) {
request
.get('/meals/brokenroute')
.expect(404)
.expect(function(res) {
ok('message' in res.body, '"message" key missing');
})
.end(done);
});
我發現的最佳解決方案(僅使用普通快遞):
app.get('/allMeals', film.getAllMeals, END);
app.get('/meals/:id', film.getMealInfo, END);
app.get('/meals/:id/options',meal.getHealthyMealoptions,END);
function END(req,res){
res.end();
//note that this wont call next...
}
//all errors are handled below
app.get('*', function(req, res) {
res.status(404).end();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.