Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 539
JuJoDi Avatar asked Apr 24 '14 14:04

JuJoDi


People also ask

What is Express json ()?

json() is a built-in middleware function in Express. This method is used to parse the incoming requests with JSON payloads and is based upon the bodyparser. This method returns the middleware that only parses JSON and only looks at the requests where the content-type header matches the type option.

What is Express () in ExpressJS?

Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application. It's a layer built on the top of the Node js that helps manage servers and routes.

Which method is used to send the content in ExpressJS?

send() Function. The res. send() function basically sends the HTTP response. The body parameter can be a String or a Buffer object or an object or an Array.

How do I find my Express Version?

You can use the package. json file to get the Express version. Show activity on this post. Navigate to the project folder type the command npm list express Note: On wrong path of project fodder it will show empty message.


2 Answers

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     } }); 
like image 185
Willie Chalmers III Avatar answered Sep 22 '22 13:09

Willie Chalmers III


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(); }); 
like image 44
mscdex Avatar answered Sep 21 '22 13:09

mscdex