[英]How to handle “Cannot <METHOD> <ROUTE>” in Express?
As a minimal example, consider following code: 作为最小的示例,请考虑以下代码:
var express = require('express');
var bodyparser = require('body-parser');
var app = express();
app.use(bodyparser.json());
app.use(errorhandler);
function errorhandler(err, req, res, next) {
res.setHeader('Content-Length', 0);
res.status(500).end();
}
app.post('/example', function(req, res) {
res.setHeader('Content-Length', 0);
res.status(200).end();
});
var server = app.listen(3000, function() {
console.log('server listening on http://%s:%s ...', server.address().address, server.address().port);
});
When I, for example, now try a PUT
on /example
, I get a Cannot PUT /example
message with 404
status code. 例如,当我现在在
/example
上尝试PUT
时,我收到一条Cannot PUT /example
消息,带有404
状态代码。 The same is true for all other routes and methods I did not declare. 对于我未声明的所有其他路由和方法,也是如此。 My error handler is only getting called on actual errors within a route or the body parser itself.
我的错误处理程序仅在路由或正文解析器本身中的实际错误上被调用。
Is there a way to handle them by myself? 有没有办法自己处理? I am using Express4.
我正在使用Express4。
Define a general handler with no route after all other use/get/post/etc: 在所有其他use / get / post / etc之后定义没有路由的一般处理程序:
app.use(function(req, res, next){
res.status(404);
res.render(...);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.