Home > Net >  Access to XMLHttpRequest has been blocked by CORS policy in Node Express and React Axios
Access to XMLHttpRequest has been blocked by CORS policy in Node Express and React Axios

Time:01-10

I'm running node server on localhost port 5500 and react on localhost port 3000 and using Axios to make requests to the node backend. if I do this with Axios setting axios.defaults.withCredentials = true I get an error. But when I do this with axios.defaults.withCredentials = false it works without any errors. Why do I change the axios withCredentials = true because I want to access the cookie from the request in the backend. The cookie is set in the front-end react

Error:

Access to XMLHttpRequest at 'http://localhost:5500/user/auth' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

I'm trying to set origin to cross middleware but it doesn't work:

app.use(cors({origin: 'http://localhost:3000'}));

Middleware Order:

app.use(cors({origin: 'http://localhost:3000'}));
app.use(express.json());
app.use(cookieParser());
app.use(express.urlencoded({ extended: false }));

CodePudding user response:

Looks like you are missing Access-Control-Allow-Credentials header in the response from your server. Try and update cors configuration:

app.use(cors({
  credentials: true,
  origin: "http://localhost:3000"
}));
  • Related