CORS problem in production mode
-
Hello,
My webapp made with Quasar works well in development with my API, in local, but not in production when I put everything on Heroku:
my-webapp.herokuapp.com —> my-api.herokuapp.com
results in:
“XMLHttpRequest cannot load https://my-api.herokuapp.com/xxx/token. Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘https://my-webapp-dev.herokuapp.com’ is therefore not allowed access. The response had HTTP status code 401.”
My webapp on Heroku (made with Quasar), hosted from a little
server.js
file:const express = require('express'); const app = express(); const history = require('connect-history-api-fallback'); const allowCrossDomain = (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'); // intercept OPTIONS method if (req.method === 'OPTIONS') { res.send(200); } else { next(); } }; app.use(allowCrossDomain); app.use(history()); app.use(express.static(__dirname + '/dist')); app.set('port', (process.env.PORT || 8080)); app.listen(app.get('port'), () => { console.log(`Server launched on ${process.env.port || 8080}`); });
The file app.js on my API on Heroku looks nearly the same, but with the
cors
middleware.Any idea on how to deal with this CORS problem ?
-
Okay I have found a solution:
The
cors
module have to be used with anapp.option()
when havingpreflight
errors.
So this works , on the API server:app.options('*', cors()); app.use(cors());
No need to add anything on the webapp part to work.