Home > Net >  How to fix CORS error in my axios request in nextjs app
How to fix CORS error in my axios request in nextjs app

Time:03-18

So I am getting this error when trying to make an axios call to my api on another localhost. How can I fix this. I am using Nextjs, ts and axios.

Here is the function (it is poorly written, just for testing in the meantime):

  const GetPartners = (e: { preventDefault: () => void; }) => {
      e.preventDefault();
      let token: string =
        "//This is normally correct just changed for question";
      axios
        .get(
          "http://localhost:7071/api/Partners",
          {
            headers: {
              Authorization: "Bearer "   token,
            },
          }
        )
        .then(res => console.log(res.data));
    } 
      return (
      <div className={styles.container}>
        <button onClick={GetPartners}>Get Partners</button>
      </div>
    );
  };
  
  export default Home;
  

and the error:

Access to XMLHttpRequest at 'http://localhost:7071/api/Partners' from origin 'http://localhost:3000' 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.

CodePudding user response:

Do you have access to http://localhost:7071 ? if so, that application needs to set to either wildcard allow everything localhost * or Access-Control-Allow-Origin: http://localhost:3031 in the header.

This has nothing to do with your request but with the response from the host to allow your request.

If you do not have control of that application in this or another environment then using a proxy to rewrite maybe another option.

You can review the topic in more detail here

CodePudding user response:

A CORS preflight request is a CORS request that checks to see if the CORS protocol is understood and a server is aware using specific methods and headers.

So in your case when you are making a request from localhost:3000 to localhost:7071 the origin is different so a preflight request is being made.

This request is getting failed because you might have not allowed accepting requests from different origins at the localhost:7071 server or we can say that you have not enabled CORS at this server.

If you are using NodeJS server and using ExpressJS middleware then you can easily enable CORS using CORS middleware. You just need to do below thing:

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

But beware of consequences of using CORS in the production environment, so you should either use it on dev mode only or at production cautiously.

CodePudding user response:

I ended up fixing it. I added this piece of code to my local.settings.json and it fixed it, hope someone finds this useful!

"Host": {
    "CORS": "*"
  }
  • Related