在邮递员上,当我向我的后端Api发送获取请求时,我可以得到响应,但在我的应用程序中,我只会获得未经授权的401

时间:2019-04-14 12:44:30

标签: reactjs express axios

我有一个api,我正在使用passport.js。当用户登录时,我给他们JWT并将axios默认标头设置为令牌。

axios.defaults.headers.common["Authorization"] = token;

我在Postman上发送请求时一切正常,但在我的React App上不起作用(除了我的默认测试路径)

router.get("/test", (req, res) => res.json({ msg: "User works" }));

我在快速应用程序中添加了cors,但没有用。

这是我的后端路线

router.get(
  "/getuserclass",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    User.findOne({ _id: req.user.id })
      .populate("classes", { _id: 1, name: 1 })
      .then(user => res.json(user))
      .catch(() => {
        return res.status(403).json({ msg: "Not found" });
      });
  }
);

这是我的获取请求

axios
      .get("/api/users/getuserclass", {
        withCredentials: true,
        crossdomain: true
      })
      .then(response => {
        console.log(response.data);
      })
      .catch(error => {
        console.log(error.response);
      });

在React应用上,它给出了此错误

401 unauthorized

0 个答案:

没有答案