0

I created a Node/Express API to post data to my mongoDB atlas database from my React frontend using axios. It works just fine in postman and my other POST/GET requests work fine. But when I try to submit some simple data from a form I get this error:

Access to XMLHttpRequest at 'https://backendAPI' from origin 'http://frontend' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I specifically included the 'Access-Control-Allow-Origin' header on my backend but I still keep getting this error.

Here's the code for handling CORS:

app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header(
      "Access-Control-Allow-Headers",
      "Origin, X-Requested-With, Content, Accept, Content-Type, Authorization"
    );
    res.header(
      "Access-Control-Allow-Methods",
      "GET, POST, PUT, DELETE, PATCH, OPTIONS"
    );
    next();
});

And here's the axios request from my frontend:

const submitData = (e) => {
    e.preventDefault();
    
    const config = {
        method: "post",
        url: "https://endpoint",
        data: {
            //some data
        }
    }

    axios(config)
        .then((result) => console.log(result))
        .catch((error) => console.log(error))
}

Everything works fine when I use postman but making requests from localhost or the site hosted on netlify I get this error.

I tried making requests from both localhost and the live site but the outcome is the same. Requests using postman work fine.

I'm using React for the frontend which is hosted on Netlify and Node/Express for the backend which is hosted on Render.

I also tried the solution from this question but I still get the same error.

0 Answers0