axios携带cookie
通过查阅 axios 手册我们可以发现 axios 的请求配置默认是不携带 cookie 信息的,下面讲解下如何通过修改axios中的cookie配置使其可以携带 cookie 信息。
# 1、全局设置
import axios from 'axios';
axios.defaults.withCredentials=true;
1
2
2
# 2、局部设置
如不想全局设置,在需要传递 Cookie/Session 的 axios 请求中加入以下代码 "withCredentials:true" 即可。
axios.get(url, { params: val },{ withCredentials: true }).then(function (response) {}).catch(function (error) {});
1
设置完 "withCredentials:true" 后,你会发现还不能正常访问,因为启用 "withCredentials" 之后,服务器的响应头 "Access-Control-Allow-Origin" 不能设置为通配符 " * ",不然会一直报错。 需要后端改下请求头,这里以node为例:
app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:8080');
res.header('Access-Control-Allow-Credentials', true);
next();
});
1
2
3
4
5
2
3
4
5
# 3、总结
如果想使用 axios 的 withCredentials 来传递 cookie,需要以下步骤:
1、在axios请求的参数中,写入对象属性withCredentials:true
2、服务器端响应头消息中的 'Access-Control-Allow-Origin' 不能设置为 ' * ' 号,需改成具体的id地址。
3、服务器端响应头消息中必须设置 'Access-Control-Allow-Credentials':'true'。
上次更新: 2024/01/30, 00:35:17
- 01
- linux 在没有 sudo 权限下安装 Ollama 框架12-23
- 02
- Express 与 vue3 使用 sse 实现消息推送(长连接)12-20