3

I'm using Connect.js to serve my static files in a Node.js application; however, I want to be able to make GET requests to those static files from multiple origins, so I'd like to be able to set 'Access-Control-Allow-Origin' : '*' in the response header for these static files.

My question is, how would I go about doing this with Connect? Here's my server so far:

var connect = require('connect');
var server = connect(
    connect.static(__dirname + '/public')
);
server.listen(8080); 
theabraham
  • 15,840
  • 9
  • 42
  • 41
  • maybe helpful http://stackoverflow.com/questions/3393854/get-and-set-a-single-cookie-with-node-js-http-server – Gerben Jun 07 '11 at 18:15

1 Answers1

0

Access-Control-Allow-Origin only applies to ajax requests, generally speaking. When you're serving static files, you don't need to worry about that particular header. Anyone can request those files, regardless of origin, in the default configuration.

You run into issues when you serve a regular page, and then you want to request via javascript FROM that page. Then you need to set your Access-Control-Allow-Origin policy to allow ajax requests to other domains from that particular page.

Further, you most often run into this when attempting to access a web service. Its very common to use JSONP in those cases, instead of using that particular header. Especially not * since it introduces security risks. See http://www.ibm.com/developerworks/library/wa-aj-jsonp1/ and http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/

MDN resource: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Josh

Josh
  • 12,602
  • 2
  • 41
  • 47
  • Mh... that's not really true since the same applies to fonts. So setting the Access-Control-Allow-Origin for static file is indeed needed. – enyo Sep 14 '12 at 16:55
  • Not true, How the browser can recognize if a file is static or dynamic? So, any Ajax request for all pages and resources of other domains are blocked by default without Access-Control-Allow-Origin. –  May 18 '14 at 10:44
  • Cross-site HTTP requests initiated from within scripts have been subject to well-known restrictions, for well-understood security reasons. For example HTTP Requests made using the XMLHttpRequest object were subject to the same-origin policy. In particular, this meant that a web application using XMLHttpRequest could only make HTTP requests to the domain it was loaded from, and not to other domains. Developers expressed the desire to safely evolve capabilities such as XMLHttpRequest to make cross-site requests, for better, safer mash-ups within web applications. – Josh May 19 '14 at 16:44
  • My main point is that you can load images, stylesheets, javascript files without ever worrying about Access-Control-Allow-Origin – Josh May 19 '14 at 16:46