How to check Content-Type using ExpressJS?

I have a pretty simple RESTful API, and my Express application is configured like this:

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 does not allow the request to reach mine app.postand app.getif the content type is not application/json?

Middleware should only stop the request with the wrong content type for the URL starting with /api/.

+10
source share
4 answers

This sets the middleware to /api/(as a prefix) and checks the content type:

app.use('/api/', function(req, res, next) {
  var contype = req.headers['content-type'];
  if (!contype || contype.indexOf('application/json') !== 0)
    return res.send(400);
  next();
});
+19
source

Express 4.0 , request.is() . :

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

Alternatively, you can use middleware express-ensure-ctype:

const express = require('express');
const ensureCtype = require('express-ensure-ctype');

const ensureJson = ensureCtype('json');
const app = express();

app.post('/', ensureJson, function (req, res) {
  res.json(req.body);
});

app.listen(3000);
+1
source

An express validator is a good module for checking input . It provides the middleware needed for any checks. In your case, something like:

const { check, validationResult } = require('express-validator')
app.use('/api/', [
   check('content-type').equals('application/json')
 ], function(req, res, next) {
   const errors = validationResult(req);
   if (!errors.isEmpty()) {
     return res.status(422).json({ errors: errors.array() });
   }
   next();
});
0
source

Source: https://habr.com/ru/post/1537898/


All Articles