0

I have made an API(using expressjs) and frontend with react the API runs on localhost:5000 and React frontend on localhost:3000 , I dont know why am I getting this err in my chrome console when I try to make a request to my backend using axios This is the err

Access to XMLHttpRequest at 'http://localhost:5000/getme' from origin 'http://localhost:3000' has been blocked by CORS policy: 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.

I have applies cors policy on the backend

relevant backend code

app.use(cors());
app.get("/getme", authMiddleware.protect, (req, res, next) => {
  res.status(200).json({
    status: "success",
    user: req.loggedInUser,
  });
});

code for authMiddleware.protect function (which is obviously on backend)

module.exports.protect = async (req, res, next) => {
  const cookie = req.cookies;
  let token;

  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith("Bearer")
  ) {
    token = req.headers.authorization.split(" ")[1];
  } else if (req.cookies.token) {
    token = req.cookies.token;
  }

  if (!token) {
    // tell them to login
    console.log("no token");
    return res.status(403).json({
      status: "action",
      redirect: "login",
    });
    // return next();
  }
  try {
    // verify token
    const _id = jwt.verify(token, process.env.JWT_SECRET)._id;
    // find User
    const loggedInUser = await networking.findDoc(User, { _id });
    if (!loggedInUser) {
      // this is rare to occur
      return res.status(404).json({
        status: "action",
        redirect: "signup",
      });
    }
    req.loggedInUser = loggedInUser;
    // console.log("logged in user:", loggedInUser);
    return next();
  } catch (err) {
    // invalid signature, (handle this trivial case on backend)
    if (err.message === "invalid signature") {
      console.log("malformed"); //test again
      return res.redirect("/logout");
    }
    return next(new Error(`err in protector: ${err.message}`));
  }
};

now from frontend I am sending a get request to this getme route and I am sending token via cookies

here is my frontend axios code , the { withCredentials: true } option is set to true because I want axios to send my cookie to backend

const getUserUrl = http://localhost:5000/getme
export const getLoggedInUser = async () => {
  try {
    console.log(">>url:", getUserUrl);
    const { data } = await axios.get(getUserUrl, { withCredentials: true });
    console.log("data>>", data);
    debugger;
    if (data.success) {
      return data.user;
    } else {
      alert("some err getting user");
      return;
    }
  } catch (err) {
    console.log("err>>>", err.message);
    alert("err in axio");
  }
};
Phil
  • 141,914
  • 21
  • 225
  • 223
  • Does this help answer your question? https://stackoverflow.com/questions/43150051/how-to-enable-cors-nodejs-with-express – Brendan Bond Dec 10 '21 at 01:21
  • You should probably use `app.use(cors({ origin: true, credentials: true }))` – Phil Dec 10 '21 at 01:23
  • nope doesn't work @BrendanBond – Yuvraj Agarkar Dec 10 '21 at 01:24
  • yes this works thanks @Phil , May I know what the err was , was it because I had set withCredentials:true in axios ? – Yuvraj Agarkar Dec 10 '21 at 01:25
  • The default cors middleware options set `origin` to `*` which is incompatible with requests with credentials (as the error message says) so you need to configure `origin` to something else (`true` simply reflects the request's origin) as well as enabling the `Access-Control-Allow-Credentials` header via the `credentials` option – Phil Dec 10 '21 at 01:28

0 Answers0