首页 > 解决方案 > 快速会话 GET 与 POST 请求

问题描述

使用 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");
});

标签: node.jsaxiosexpress-session

解决方案


axios.get()只需要两个参数(不是三个)。第一个是 URL,第二个是选项。您正在传递第三个axios.get()不看的选项。因此,它永远不会看到该withCredentials: true选项,因此不会发送会话 cookie,因此您的服务器不知道如何找到会话。

所以,从这个改变:

axios.get(url,{params:data},{withCredentials: "true"})

对此:

axios.get(url,{withCredentials: "true"})

注意,没有 data 参数,axios.get()因为 GET 不发送请求正文,只有 POST 或 PUT 发送正文。请参阅此处的文档。


注意:这会经常咬人axios.post()并且.get()需要不同数量的参数。


推荐阅读