Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting default response headers in Express

I'm working on a small app running on the MEAN stack, and have hit an annoying snag: My backend app (Node with Express) is running at http://localhost:3000 and working just fine, but my frontend client app (Javascript with AngularJS) is running at http://localhost:8000, which means requests sent from Angular are received and responded to, but are rejected once they arrive because they're interpreted as coming from a different origin.

I was able to fix this with relatively little drama, by making my 'show me all the stuff' method look something like this:

exports.index = function(req, res) {
  Region.find({}, function(err, docs) {
    if(!err) {
      res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8000');
      res.json(200, { regions: docs });
    } else {
      res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8000');
      res.json(500, { message: err });
    }
  });
}

The res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8000'); line is the one that I added to tell the browser it was fine to accept the response and stop bothering me about it; the problem now is that I have to add this stupid line to every single response that's sent from anywhere, and I'm convinced I must be missing some way to just change the default headers to include the Access-Control-Allow-Origin entry forever.

In a perfect world, I'd be able to flip this on and off based on what environment the code was being executed in, but I'd totally settle for a code block in app.js that I could at least remove one time instead of trying to track down 75 instances of res.setHeader. I figure there must be a way to change the .json method hiding behind res at its base, but the docs don't offer any insight into how I might do that, not to mention whether it's a terrible idea. Any thoughts?

edit

I thought (as was suggested) that configuring application-level middleware was the key. Here's the code that I added to my app.js file:

// allow CORS:
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8000');
  next();
});

This, however, yielded the same error ("No 'Access-Control-Allow-Origin' header is present on the requested resource.") as before.

like image 469
rabdill Avatar asked Sep 03 '15 02:09

rabdill


People also ask

How do you set a response header?

Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.

What is RES header?

A response header is an HTTP header that can be used in an HTTP response and that doesn't relate to the content of the message. Response headers, like Age , Location or Server are used to give a more detailed context of the response.

What is RES locals in Express?

The res. locals is an object that contains the local variables for the response which are scoped to the request only and therefore just available for the views rendered during that request or response cycle.

Can't set headers after they are sent?

The error "Error: Can't set headers after they are sent." means that you're already in the Body or Finished state, but some function tried to set a header or statusCode. When you see this error, try to look for anything that tries to send a header after some of the body has already been written.


1 Answers

Try this one as a middleware:

app.use(function(req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
  next();
});
like image 128
Subham Avatar answered Nov 03 '22 23:11

Subham