Reputation: 1259
I would like to know how I can set the header "Content-Type": "application/json"
for every nodejs express request that comes in.
I tried both of these lines but my calls are still failing if I don't add the header myself:
app.use(function(req, res, next) {
req.header("Content-Type", "application/json");
res.header("Content-Type", "application/json");
next();
});
All of my requests are json, so I don't want the front end (Anguler) to send me this header every time if I can just set it myself from the server side.
Upvotes: 17
Views: 55770
Reputation: 477
Send headers as an object:
res.writeHead(200, {
"Content-Type": "application/json",
"Content-Length": "1234...",
});
Here you have to also specify status code, 200
means Status is OK
, learn more about status codes here : HTTP Status Codes
or use this code to set individual headers
res.setHeader("Content-Type", "application/json");
res.setHeader("Content-Length", "1234...");
Upvotes: 2
Reputation: 9
To update the request headers please add below custom middleware before bodyparser
app.use(function (req, res, next) {
req.headers['content-type'] = 'application/json';
next();
});
If still not working check the case of 'content-type' sent by your client. Put the 'content-type' in the same case
Upvotes: 1