-2

I try to connect my local backend with the fronte

   axios({
      method: "post",
      url: "http://localhost:5000/api/user/login",
      withCredentials: true,
      data: {
        email,
        password,
      },
    })
      .then((res) => {
        if (res.data.errors) {
          emailError.innerHTML = res.data.errors.email;
          passwordError.innerHTML = res.data.errors.password;
        } else {
          window.location = "/";
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

nd Reactjs. The backend works very well with the postman but when I just try to login from my front end, in the console.log I get the error message 'problem with cors'... What am I missing? and here is the error message : Access to XMLHttpRequest at 'http://localhost:5000/api/user/login' 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-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

here is the code of the function that runs after the submit

MUHESI
  • 1
  • You have to allow localhost in your backend cors config. If you are using express, try to see it: https://stackoverflow.com/questions/43150051/how-to-enable-cors-nodejs-with-express – Murilo Góes de Almeida Apr 11 '21 at 03:56

1 Answers1

1
  • Add Proxy in package.json of front end application.
 "proxy": "http://localhost:5000"
  • Next instead of full uri in axios call just call it as
axios.post('/user/login')...
  • Now inside the backend (node) directory add the following dependency using npm
npm install cors
  • Now use this inside main server file i.e server.js like below
const cors = require('cors')
app.use(cors())
Muhammad Atif Akram
  • 1,204
  • 1
  • 4
  • 12