Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 763
Freddy Bonda Avatar asked Oct 15 '18 08:10

Freddy Bonda


People also ask

How do I send a header request in node js?

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.

How do you specify Content-Type in a post request?

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.

How do I use Content-Type in node js?

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

Do I need a Content-Type header for HTTP GET requests?

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.


3 Answers

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

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

doc.

like image 194
Alex Avatar answered Sep 18 '22 22:09

Alex


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

like image 43
Yasantha Hennayake Avatar answered Sep 20 '22 22:09

Yasantha Hennayake


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");
like image 39
27px Avatar answered Sep 18 '22 22:09

27px