Search code examples
node.jshttpheader

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.


Solution

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

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

    doc.