简体   繁体   中英

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. 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.

Define a general handler with no route after all other use/get/post/etc:

app.use(function(req, res, next){
  res.status(404);
  res.render(...);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM