Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access control origin in connect (node.js)

I am running static pages via connect

     var connect = require('connect');
     connect.createServer(
     connect.static(__dirname)).listen(8080);

I have to add a response header to the above code to bypass the access control

  response.writeHead(200, {
             'Content-Type': 'text/html',
             'Access-Control-Allow-Origin' : '*'});

How do I add it to the above connect code.

like image 757
usercode Avatar asked Nov 02 '22 19:11

usercode


1 Answers

I answered this question here

Relevant 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 excellent resource for adding cors to your server.

If you got to send the cors headers with every static file that you serve and you have to use connect then do this

navigate to connect\node_modules\send\lib\send.js

look for the setHeader function in the file. This is the function that actually sets header to your static resources. Just add

res.setHeader("Access-Control-Allow-Origin", "your domain");

and all of your files will have the cors header in them

If you are just using connect to serve static files and don't require any of the other functionality consider using send instead. This way you will have access to all of it's methods directly and won't need to edit files. You can simply add headers from your create server method. Here is the 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);
like image 51
Akshat Jiwan Sharma Avatar answered Nov 09 '22 04:11

Akshat Jiwan Sharma