在node.js表示应用(失败)中的'缺less路由'error handling
我只是试图在我的app.js
或路由器文件中工作,以处理可能丢失的路由器错误。 (类似的stackoverflow解决scheme没有为我工作)
我的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's / expresserror handling软件包“ 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) });
当上面跑了; 我在terminal上出现“ response
”字时出现构build错误 。 安装相关的npm包时我没有错误。
ReferenceError: response is not defined
然后我尝试了一些我在stackover上find的build议。
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
对于更多的上下文,这里是没有通过我的尝试的testing:
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); });
我find了最好的解决scheme(仅使用纯文本):
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(); });