我有一个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