I am getting this error blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource in mern

I am currently working on a project where I am implementing Spotify authentication using React for the frontend and Node.js for the backend. Everything is working fine on the backend, but I am facing a CORS issue when trying to handle the Spotify authorization process on the frontend.

Backend (Node.js) code:


const router = express.Router();

router.use("/login", (req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "http://localhost:2002/auth/login");
  next();
});

router.get("/login", function (req, res) {
   // Your existing code to construct the authorizationURL
  const queryString = querystring.stringify({
    response_type: "code",
    client_id: "########",
    redirect_uri: "http://localhost:7001/auth/callback",
    scope: "user-library-read, user-top-read",
  });

  const authorizationURL =
    "https://accounts.spotify.com/authorize?" + queryString;

  // Redirect the user to the Spotify authorization URL
  res.redirect(authorizationURL);
});

router.get("/callback", async function (req, res) {
  // ... (Handling Spotify callback)
});

export { router as userRouter };

Frontend (React) code:

Frontend code

 export const Home = () => {
  const navigate = useNavigate();

  const handleSubmit = (e) => {
    e.preventDefault();
    axios.get('/auth/login')
      .then(response => {
        console.log("success logining in: ", response.data);
        window.location.href = response.data.authorizationURL;
      })
      .catch(error => {
        console.error('Error logging in:', error);
      });
  };

  return (
    <div>
      <h1>Login</h1>
      <form onSubmit={handleSubmit}>
        <button type="submit">Login with Spotify</button>
      </form>
    </div>
  );
};

The error I am encountering is:

Access to XMLHttpRequest at ‘https://accounts.spotify.com/authorize?response_type=code&client_id’ (redirected from ‘http://localhost:2002/auth/login’) from origin ‘http://localhost:2002’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
I tried adding CORS headers on the backend, but it didn’t resolve the issue. I suspect there might be an issue with the way I am making the API request from the frontend.

Could you please help me identify the root cause of this CORS issue and suggest a solution? Any insights or code modifications would be greatly appreciated.

Thank you!