I answered this question here
Corresponding code
var http = require("http"); var connect = require('connect'); var app = connect() .use(connect.logger('dev')) .use(connect.static('home')) .use(function(req, res){ res.setHeader("Access-Control-Allow-Origin", "http://example.com"); res.end('hello world\n'); }); var server = http.createServer(app); server.listen(9999, function () { console.log('server is listening'); });
Enable cors provides an excellent resource for adding cors to your server.
If you need to send cors headers with every static file you serve and you need to use connect, do this
go to connect\node_modules\send\lib\send.js
find the setHeader function in the file. This is the function that actually sets the title for your static resources. Just add
res.setHeader("Access-Control-Allow-Origin", "your domain");
and all your files will have a cors header
If you just use connect to serve static files and don't require any other functions, use send instead. Thus, you will have access to all these methods directly and will not need to edit files. You can simply add headers from your server creation method. Here is a sample code
var http = require("http"); var connect = require('connect'); var send = require('send'); var url = require('url'); var app = http.createServer(function(req, res){ // your custom error-handling logic: function error(err) { res.statusCode = err.status || 500; res.end(err.message); } // your custom directory handling logic: function redirect() { res.statusCode = 301; res.setHeader('Location', req.url + '/'); res.end('Redirecting to ' + req.url + '/'); } function setRoot(){ res.setHeader("Access-Control-Allow-Origin", "http://example.com"); return './public'; } function setIndex(){ res.setHeader("Access-Control-Allow-Origin", "http://example.com"); return '/index.html'; } send(req, url.parse(req.url).pathname) .root(setRoot()).index(setIndex()) .on('error', error) .on('directory', redirect) .pipe(res); }).listen(3000);
source share