Freddy Bonda
Freddy Bonda

Reputation: 1259

Nodejs how to set content-type header for every request

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

Answers (3)

27px
27px

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

Yasantha Hennayake
Yasantha Hennayake

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

Sasha
Sasha

Reputation: 5944

Response object has to use .setHeader instead of .header:

app.use(function(req, res, next) {
    res.setHeader("Content-Type", "application/json");
    next();
});

doc.

Upvotes: 35

Related Questions