New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add convenience methods for CORS support #21

Closed
jeremydaly opened this Issue Mar 28, 2018 · 1 comment

Comments

Projects
None yet
1 participant
@jeremydaly
Copy link
Owner

jeremydaly commented Mar 28, 2018

This seems like too common of a use case to require middleware every time to accomplish this. The method below is one way of handling preflight requests now.

api.options('/*', function(req,res) {
  // Add CORS headers
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
  res.status(200).send({});
})

There are six response headers documented here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

  • Access-Control-Allow-Origin
  • Access-Control-Expose-Headers
  • Access-Control-Max-Age
  • Access-Control-Allow-Credentials
  • Access-Control-Allow-Methods
  • Access-Control-Allow-Headers

These could easily be packaged in a configuration object when calling something like:

res.cors({ 
  origin: 'example.com', 
  methods: 'GET, PUT, POST, DELETE, OPTIONS', 
  headers: 'Content-Type, Authorization',
  maxAge: 84000
})

I'm not sure this is much shorter, but it could always come with defaults.

@jeremydaly jeremydaly added this to the v0.5 milestone Apr 6, 2018

@jeremydaly

This comment has been minimized.

Copy link
Owner

jeremydaly commented Apr 23, 2018

Implemented a version of this with some standard defaults. You can simply call res.cors() and it will add all the defaults. You can override defaults as well as make incremental changes by passing in an options object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment