node.js - 快速会话 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");
});
解决方案
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()
需要不同数量的参数。
推荐阅读
- java - 如何在 Servlet 中使用 DAO 设计模式 appoarch 将用户输入存储到 MongoDB?
- wordpress - gatsby-source-wordpress 插件:我无法将数据从 WP 拉入 Gatsby(连接错误)
- react-native - 如何在文本组件中放置一个“<”,React Native
- windows - 在 Windows 批处理脚本中时间不变
- sql - 我正在尝试为 sql 正则表达式找到一个模式
- sql - 基于功能的索引在 oracle 12c 中不起作用
- linux - 用于创建 ext2/3/4 文件系统的 UEFI 应用程序
- node.js - 从 NodeJs 和 Kerberos 身份验证中选择 Impala 表
- javascript - 将php插入JS文件
- python - 检查单词列表并使用唯一列表从页面源代码返回找到的单词