How do I check Content-Type using ExpressJS?
As an alternative, you can use the express-ensure-ctype
middleware:
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);
This mounts the middleware at /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();
});
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.send(400);
} else {
// Do logic here
}
});
Get content type from the request by using this.
req.get('Content-Type')
Example :
app.post("/api/test", (req, res) => {
console.log("Request type :", req.get('Content-Type'));
//your code
})