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.
setHeader() to set header of our request. The header tells the server details about the request such as what type of data the client, user, or request wants in the response. Type can be html , text , JSON , cookies or others.
In a POST request, resulting from an HTML form submission, the Content-Type of the request is specified by the enctype attribute on the <form> element.
use(function(req, res, next) { req. header("Content-Type", "application/json"); res. header("Content-Type", "application/json"); next(); });
Nope, Content-Type is not a required field. It's not mandatory per the HTTP 1.1 specification. Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body.
Response object has to use .setHeader
instead of .header
:
app.use(function(req, res, next) {
res.setHeader("Content-Type", "application/json");
next();
});
doc.
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
res.writeHead(200, { "Content-Type": "application/json" });
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
res.setHeader("Content-Type", "application/json");
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