Home > Blockchain >  Failed to load resource: the server responded with a status of 401 (Unauthorized) in REACT and NODE.
Failed to load resource: the server responded with a status of 401 (Unauthorized) in REACT and NODE.

Time:05-08

This is REACT js client side code in console error is this 1.Failed to load resource: the server responded with a status of 401 (Unauthorized) 2. Uncaught TypeError: inventories.map is not a function

 useEffect(() => {
        setDataLoading(true);
        const url = `http://localhost:5000/inventoryByEmail?email=${user.email}`;
        fetch(url, {
          headers: {
            authorization: `Bearer ${localStorage.getItem("access-token")}`,
          },
        })
          .then((res) => res.json())
          .then((data) => {
            setInventories(data);
            setDataLoading(false);
          });
      }, [user]);

This is Server site Nodejs code

function verifyJWT(req, res, next) {
  const authHeader = req.header.authorization;

  if (!authHeader) {
    return res.status(401).send({ message: "unauthorized access" });
  }
  const token = authHeader.split(" ")[1];
  jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
    if (err) {
      return res.status(403).send({ message: "Forbidden access" });
    }
    req.decoded = decoded;
    next();
  });
}

and this is api Route

app.get("/inventoryByEmail", verifyJWT, async (req, res) => {
      const decodedEmail = req.decoded.email;
      const email = req.query.email;
      if (email === decodedEmail) {
        const query = { email: email };
        const cursor = inventoryCollection.find(query);
        const result = await cursor.toArray();
        res.send(result);
      } else {
        res.status(403).send({ message: "forbidden access" });
      }
    });

How to slove this issue? thanks so much for your time!

CodePudding user response:

in your function verifyJWT it's : req.headers.authorization; or if you want to get the token : req.headers.authorization.split(' ')[1];

  • Related