快速会话 GET 与 POST 请求

Express Sessions GET vs POST requests

我可以在使用 post 方法时访问会话对象数据,但在使用 get 时会话对象数据为空 method.How 我可以使用 get 方法访问会话对象数据吗? 我正在使用快速会话。

前端代码

对于POST方法

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

对于 GET 方法

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

后端代码 get 和 post 请求的中间件。

router.use((req: Request, res: Response, next: NextFunction) => {
  console.log(req);
  if (req.session && req.session.username) next();
  else res.status(401).send("Unauthorized");
});

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() 需要不同数量的参数。