Skip to content

Instantly share code, notes, and snippets.

@cahlan
Created November 19, 2015 03:33
Show Gist options
  • Save cahlan/cb97d415ff3dfd66ecce to your computer and use it in GitHub Desktop.
Save cahlan/cb97d415ff3dfd66ecce to your computer and use it in GitHub Desktop.
Node + CORS

What if we were trying to access data from a domain we weren't hosting on? In other words, what if we had a site on http://example.com but we needed to get data from another domain of ours, http://awesome.com? Because of Same-origin policy implemented by browsers, we can't do this. By default, browsers will only allow Javascript to manipulate or access API resources that originate from the same domain. There are times where we do want communication to happen across domains, which is why we can implement special HTTP headers that define a cross-origin policy and thus allow us to access data across separate domains.

In Node, use this header for simple cross site request blocking:

res.setHeader('X-XSS-Protection', '1; mode=block');

If we want to have data accessible from other domains, we'd need to add the appropriate ‘Access-Control-Allow-Origin’ headers to make this possible:

function handleRequest(req, res) {
  // Everything is 200 OK
  res.statusCode = 200;
  
  // We’re sending JSON
  res.setHeader('Content-Type', 'application/json');
  
  // Allow data access from other domains
  res.setHeader('Access-Control-Allow-Origin', '*');
  
  // Don’t allow script execution from other domains
  res.setHeader('X-XSS-Protection', '1; mode=block');
  res.setHeader('X-Frame-Options', 'SAMEORIGIN');
  res.setHeader('Content-Security-Policy', "default-src 'self'");
  
  var result = {message: 'Hello World'};
  var jsonResult = JSON.stringify(result);
	res.end(result);
}

var http = require('http');
var server = http.createServer();
server.on('request', handleRequest)
server.listen(12200);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment