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/
.
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.
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.
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.
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.
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 } });
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With