2

I have an express application with many routes:

app.get('foo/bar', function(res, res, next) { ... });
app.post('foo/bar', function(res, res, next) { ... });
app.get('another/one/path', function(res, res, next) { ... }));

And I need to send cross domain AJAX requests to this application. So, I need to send correct Access-Control-Allow-Methods on OPTIONS requests. For example, if the request is OPTIONS 'foo/bar', then the Access-Control-Allow-Methods header should be equal GET,POST. I see that if I send OPTIONS request in Express framework I already get a correct list of methods in response body. For example if I I send OPTIONS 'foo/bar' I get a response with body GET,POST. Now, I want to send GET,POST in Access-Control-Allow-Methods header too. I'm trying to find an easy solution to do this. I don't want to add an options routes, because I already have more than 200 routes in the application.

Ildar
  • 3,808
  • 7
  • 45
  • 81
  • Possible duplicate of [How to allow CORS in Express/Node.js?](http://stackoverflow.com/questions/7067966/how-to-allow-cors-in-express-node-js) – Dave Newton Dec 05 '15 at 15:37

2 Answers2

4

Simplest solution would be to use cors npm package.

var express = require('express')
  , cors = require('cors')
  , app = express();

app.use(cors());
Kunal Kapadia
  • 3,223
  • 2
  • 28
  • 36
2

If you are looking to roll your own, this will get you started.

app.use(function(req, res, next) {
    var oneof = false;
    if (req.headers.origin) { //req.headers.origin.match(/whateverDomainYouWantToWhitelist/g) ) {
        res.header('Access-Control-Allow-Origin', req.headers.origin);
        oneof = true;
    }
    if (req.headers['access-control-request-method']) {
        res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);
        oneof = true;
    }
    if (req.headers['access-control-request-headers']) {
        res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
        oneof = true;
    }
    if (oneof) {
        res.header('Access-Control-Max-Age', 60 * 60 * 24 * 365);
    }

    // intercept OPTIONS method
    if (oneof && req.method == 'OPTIONS') {
        res.sendStatus(200);
    } else {
        next();
    }
});
Gary
  • 2,866
  • 1
  • 17
  • 20