|
目标: vue中实现session登录
步骤: 1. 前端代码配置 加上 axios.defaults.withCredentials=true; // 让ajax携带cookie(自动携带本地所有cookie)s
axios.defaults.withCredentials=true;
// 使用create方法创建axios实例
const Service = axios.create({
baseURL: ConfigBaseURL, //1. 设置默认地址
timeout: 7000 // 2. 请求超时时间
})
2. 后端代码配置(nodejs) 加上:res.header("Access-Control-Allow-Credentials", "true");、 app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:5173");
res.header("Access-Control-Max-Age", "3600");
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Headers", "X-Requested-With,X_Requested_With,Content-Type");
res.header("Access-Control-Allow-Methods", 'PUT, POST, GET, DELETE, OPTIONS');
// res.header("Access-Control-Allow-Credentials", "true");
next();
});
除此之外注意:当前端配置withCredentials=true时, 后端配置Access-Control-Allow-Origin不能为*, 必须是相应地址 否则报错: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiat 注意: 1. 当前端配置 withCredentials=true 时, 后端配置 Access-Control-Allow-Origin 不能为 * , 必须是相应地址 2. 当配置 withCredentials=true 时, 后端需配置 Access-Control-Allow-Credentials 3. 当前端配置请求头时, 后端需要配置 Access-Control-Allow-Headers 为对应的请求头集合 参考:https://juejin.cn/post/6844903748288905224 |
|
|