Home > Net >  Can't authorize user in jwt - Node.js react.js
Can't authorize user in jwt - Node.js react.js

Time:08-08

When user login , it should redirects to homepage and gets posts.

I make api call in react but it returns 401 unauthorized . If I do with same auth header on postman it returns proper data.

    const getPosts = async () => {
    await axios
      .get("/api/post", {
        headers: { authorization: "Bearer"   localStorage.getItem("token") },
      })
      .then((res) => setPosts(res.data));};
     useEffect(() => {getPosts();},[]);

Server Side

  router.get("/api/post", authToken, async (req: Request, res: Response) => {
  const posts = await Post.find({ relations: ["user"] });

  return res.json(posts);
});

middleware

    const authToken = (req: Request, res: Response, next: NextFunction) => {
  const token = req.headers.authorization?.split(" ")[1];

  if (token == null) return res.sendStatus(401);

  jwt.verify(token, "SECRET", (err, decode) => {
    if (err) return res.sendStatus(403);

    res.locals = { ...res.locals, token: decode };
    next();
  });
};

CodePudding user response:

You are missing the whitespace in your headers:

headers: { authorization: "Bearer "   localStorage.getItem("token") }
  • Related