Reputation: 465
I have CORS issue and spend a lot of time trying to figure it out, so I decide to ask a question here. I have keystone app on a subdomain to the domain where is my angular 5 app. On localhost everything works ok but, but when I put my files to the server and try open my angular app I get this error:
Failed to load http://xxxxxxxx.com/label: Request header field params is not allowed by Access-Control-Allow-Headers in preflight response.
I have added this lines to my keystone.js file:
keystone.set('cors allow origin', true);
keystone.set('cors allow methods', true);
keystone.set('cors allow headers', true);
And this line in routes/index.js:
app.all('/*', keystone.middleware.cors);
And I tried add this to routes/index.js:
app.options('/*', function(req, res) {
res.header("Access-Control-Allow-Credentials", "true");
res.header('Access-Control-Allow-Methods', 'GET,POST');
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.sendStatus(200);
});
But I still get the same error. Any suggestions how to fix that?
Upvotes: 0
Views: 1005
Reputation: 341
I am also using Keystone.js and I am editing /routes/middleware.js by adding the below lines at the end of file:
/*
* CORS
*/
exports.setCors = function (req,res,next) {
res.header('Access-Control-Allow-Origin', '*.*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
}
Upvotes: 0
Reputation: 4507
Well the error message says it all (admittdely not very clearly) - Request header field params is not allowed by Access-Control-Allow-Headers in preflight response. - this means that there is a request header called params
which isn't included in the Access-Control-Allow-Headers (ACAH) response header.
Change the ACAH to be this:
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, params");
and you should be fine.
Not that adding a separate package won't also solve the problem, but you don't need to add a new package to get this to work.
Upvotes: 0
Reputation: 5858
Install this package https://www.npmjs.com/package/cors and manage your CORS domains.
basic usage
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
Upvotes: 1