Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make web service available for cross-domain access?

I have this API built with Nodejs-Express:

app.get('/api/v1/:search', function(req, res){
        var response = {}   
        res.contentType('application/json');
                // process req.params['search']
                // build and send response
                res.send(response, response.status_code);
          });

However, I need to make a client that will sit on another domain. How do I fix this code so it can be called through like JQuery $.ajax, etc.

like image 849
quarks Avatar asked Nov 09 '11 16:11

quarks


1 Answers

Something like this should work:

//Middleware: Allows cross-domain requests (CORS)
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');

    next();
}

//App config
app.configure(function() {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.cookieParser());
  app.use(express.session({ secret: 'secret' }));
  app.use(express.methodOverride());
  app.use(allowCrossDomain);
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});
like image 76
evilcelery Avatar answered Sep 29 '22 13:09

evilcelery