Home > Software engineering >  CORS error 'No 'Access-Control-Allow-Origin' header is present on the requested resou
CORS error 'No 'Access-Control-Allow-Origin' header is present on the requested resou

Time:07-13

From my understanding this is fairly common. No issues on local however when I deploy my frontend (react) and my backend (node/express) to two different heroku applications I get this error:

Access to XMLHttpRequest at 'https://myapp-server.herokuapp.com/endPoint' from origin 'https://myapp-frontend.herokuapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Please note im not using the actual application names in the question for privacy.

So I have this in my node/express server

const cors = require('cors');
app.use(cors())

Which didnt work, So i added this:

let corsOptions = {
    origin: ['https://myapp-frontend.herokuapp.com'],
}

app.use(cors(corsOptions))

Which also didnt work, so finally I added some headers like this (and also added them to my endpoints)

app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.setHeader("Access-Control-Allow-Origin", "https://myapp-frontend.herokuapp.com");
    res.header(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept"
    );
    next();
});

Is there something I am missing? I have seen suggestions around browser extensions but wouldnt that restrict access to the browsers device only?

Thanks for any help!

CodePudding user response:

Please go through this link:

https://www.codingdeft.com/posts/nodejs-react-cors-error/#configuring-environment-files-in-heroku

You have to configure environment files in heroku as well.

CodePudding user response:

What server to you use? Maybe requests are being blocked before they actually reach the node.js server.

  • Related