Search code examples
javascriptnode.jsexpressexpress-4

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.


Solution

  • 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(...);
    }