How should i configure CORS to avoid https request errors?

Viewed 40

I get the following message: "Access to XMLHttpRequest at 'api-domain' from origin 'website-domain' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status"

This is how i handle the requests in my app.js file.

app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Methods',
'OPTIONS, GET, POST, PUT, PATCH, DELETE'
);
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader('Access-Control-Expose-Headers', 'Authorization');
next();
});

I tried using my domain instead of the '*', but it doesnt work either.

Am i missing something here?

edit: i also tried this solution to handle preflight requests but it didnt work

module.exports = function (req, res, next) {
// CORS headers
res.header("Access-Control-Allow-Origin", "YOUR_URL"); // 
restrict it to the required domain
res.header("Access-Control-Allow-Methods", 
"GET,PUT,POST,DELETE,OPTIONS");
// Set custom headers for CORS
res.header("Access-Control-Allow-Headers", "Content- 
type,Accept,X-Custom-Header");

if (req.method === "OPTIONS") {
    return res.status(200).end();
}

return next();
};
1 Answers

First remove all of your existing header. Do it with cors package.

Step 1: install the cors npm install cors

Step 2: import it var cors = require('cors')

Step 3: simply use in app. app.use(cors())

You can configure cors package. See details from here

Related