VersifiXion
VersifiXion

Reputation: 2292

"No 'Access-Control-Allow-Origin' header is present on the requested origin" CORS not working (with npm package CORS)

I'm doing a project with a React app + a NodeJS server.

I have my app on port 3000 and my server on port 5000.

I want to do a POST request on "/api/users/login", but when I do, I have this message :

Access to XMLHttpRequest at 'http://localhost:5000/api/users/login' 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.

Here's a part of the code of the client, where I always go in the catch :

axios
    .post(`${process.env.REACT_APP_API_URL}/api/users/login`, userData)
    .then(res => {
      const { token } = res.data;
      localStorage.setItem("jwtToken", token);
      setAuthToken(token);
      const decoded = jwt_decode(token);
      dispatch(setCurrentUser(decoded));
      window.location.href = "/";
    })
    .catch(err => {
      console.log("err ", err);
      dispatch({
        type: GET_ERRORS,
        payload: err.response.data
      });
    });

Here's a part of the server :

const cors = require("cors");

const whitelist = [
  "http://localhost:3000",
  "http://localhost:5000",
  "https://ofilms.herokuapp.com"
];
const corsOptions = {
  origin: function(origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true);
    } else {
      callback(new Error("Not allowed by CORS"));
    }
  }

router.post("/api/users/login", cors(corsOptions), (req, res) => {
  console.log("corsOptions ", corsOptions);

  const email = req.body.email;
  const password = req.body.password;

Documentation of the package : https://www.npmjs.com/package/cors

Upvotes: 0

Views: 1144

Answers (1)

Firmino Changani
Firmino Changani

Reputation: 959

Have you tried using cors without the custom options?

router.post("/api/users/login", cors(), (req, res) => {});

Or even

app.use(cors())

Upvotes: 1

Related Questions