mjackson/mach

CORS support

Opened this issue · 3 comments

In express you can enable CORS support with:

app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
 });

Didn't see anything in documentation surrounding this, but would appreciate the feature.

Actually I guess setting headers is supported, I will experiment and submit a pull request with equivalent documentation for mach.

I've thought about what a mach.cors middleware might look like, but haven't come up with an API yet that makes it any easier to use CORS than just setting the headers manually.

If you just wanna set Access-Control-Allow-Origin: * on every response, you can do it in a middleware:

function cors(app) {
  return function (conn) {
    return conn.call(app).then(function () {
      conn.response.setHeader('Access-Control-Allow-Origin', '*');
    });
  };
}

app.use(cors);

But as far as I understand it, CORS headers can (and probably should) change on a per-endpoint basis. This makes me think that CORS support should be integrated directly into the router somehow. If you have any ideas of an elegant way to express CORS behavior on a per-route basis, I'm open to suggestions! :)

it should happen before routing, a lookup of the request's host header. maybe something like:

cors = require('cors')(function (host) {
  return (host === 'localhost');
});

app.use(cors);

the module itself encapsulates the setting of the headers, so might need more options on that.