使用post方法时可以访问会话对象数据,但是使用get方法时可以访问会话对象数据。如何使用get方法访问会话对象数据。 我正在使用快速会话。
前端代码
对于POST方法
axios.post(url,{params:data},{withCredentials: "true"})
对于GET方法
axios.get(url,{params:data},{withCredentials: "true"})
后端代码 获取和发布请求的中间件。
router.use((req: Request, res: Response, next: NextFunction) => {
console.log(req);
if (req.session && req.session.username) next();
else res.status(401).send("Unauthorized");
});
答案 0 :(得分:2)
axios.get()
仅接受两个参数(而不是三个)。第一个是URL,第二个是选项。您正在通过axios.get()
不在的第三点传递选项。因此,它永远不会看到withCredentials: true
选项,因此不会发送会话cookie,因此您的服务器也不知道如何查找会话。
所以,从此更改:
axios.get(url,{params:data},{withCredentials: "true"})
对此:
axios.get(url,{withCredentials: "true"})
请注意,axios.get()
没有数据参数,因为GET不会发送请求正文,只有POST或PUT会发送正文。请参阅文档here。
注意:这会定期axios
咬人。 .post()
和.get()
需要不同数量的参数。