openfaas-incubator / node8-express-template

Node.js 8 template for OpenFaaS with HTTP via Express.js
MIT License
15 stars 18 forks source link

Suggestion - support OPTIONS verb #7

Open nerdguru opened 6 years ago

nerdguru commented 6 years ago

Hi there,

When using OpenFaaS and Node.js to build an API accessible by Javascript running in the browser, browsers will make a preflight OPTIONS call prior to a POST. As currently constructed, a function can respond to POST and GET verbs where they can choose to alter the Access-Control-Allow-Origin header so that CORS calls can be made in the browser, but not OPTIONS.

As a workaround for my own code, I simply added the following in index.js on line 85:

app.options("/*", function(req, res, next){ 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.send(200); });

However, I'm not sure that's the best long term fix. I thought I'd document this here and I'm willing to submit a PR for what I've done if you're interested.

alexellis commented 5 years ago

I am not sure that opening CORS up to any origin makes sense.

Access-Control-Allow-Origin', '*'

Perhaps you could specify a list of domains / URIs at least?

nerdguru commented 5 years ago

Agreed that's not what you'd set it to for a production deployment, but my point was more that there isn't a mechanism to set it currently at all for OPTIONS.

alexellis commented 5 years ago

Does this pass all the way through from the API Gateway without any issues?

If so then perhaps you could fork this repo and use faas-cli template pull as needed for your custom override. There may be an issue tracking CORS control at a wider level over at openfaas/faas (have a search through the issues)

Some people run a reverse proxy in front of the gateway and where they serve their static content (assuming this is your current issue) as a work-around. There is also documentation over at https://docs.openfaas.com/ on CORS. For more info perhaps @kenfdev could advise?

Alex

nerdguru commented 5 years ago

OK, so I played around with this today and the fix is really simple, see my PR. The template already could pass control of the response headers for GET and POST verbs, all I did was add another line per sub-template to do the same for OPTIONS so now a function developer can handle CORS headers as they see fit without requiring a reverse proxy.