node.jsexpress

How do I check Content-Type using ExpressJS?


I have a pretty basic RESTful API so far, and my Express app is configured like so:

app.configure(function () {
  app.use(express.static(__dirname + '/public'));
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
});

app.post('/api/vehicles', vehicles.addVehicle);

How/where can I add middleware that stops a request from reaching my app.post and app.get if the content type is not application/json?

The middleware should only stop a request with improper content-type to a url that begins with /api/.


Solution

  • If you're using Express 4.0 or higher, you can call request.is() on requests from your handlers to filter request content type. For example:

    app.use('/api/', (req, res, next) => {
        if (!req.is('application/json')) {
            // Send error here
            res.sendStatus(415);
        } else {
            // Do logic here
        }
    });