doubleyong
管理员
管理员
  • 最后登录2026-05-25
  • 发帖数1198
  • 最爱沙发
  • 喜欢达人
  • 原创写手
  • 社区居民
  • 忠实会员
阅读:4800回复:0

[vue]vue中使用session登录的方法及注意事项

楼主#
更多 发布于:2022-10-25 11:18
目标: 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
知识需要管理,知识需要分享
游客


返回顶部

公众号

公众号