I have a white list of URLs
I have trouble using it with GET requests, but with POST it works.
For POST everything works.
For GET I took an example from the Express website. It doesn't work. Cors allowed GET requests from any domain.
const allowedList =["http://localhost:3000", "http://localhost:3001"]
const corsOptions = {
origin: function (origin, callback) {
if (allowedCORS.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
const corsOptionsGet = function (req, callback) {
let corsOptions;
if (allowedCORS.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true }
} else {
corsOptions = { origin: false }
}
callback(null, corsOptions)
}
router.post("/add-item", cors(corsOptions), addItem);
router.get("/get-item", cors(corsOptionsGet), getItem);
CodePudding user response:
How are you calling your server? if you are using tools like Postman
or curl
the Origin header is not set by default and you need to manually add it to the request header.
CodePudding user response:
I don't really understand your allowedList is not in the function so how you set that cors setting to work ?
const allowedList =["http://localhost:3000", "http://localhost:3001"]
const corsOptions = {
origin: function (origin, callback) {
if (allowedList.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'), false)
}
};
app.use(cors(corsOptions));