Thinkphp5和Vue前后端分离的情况下共享验证码session

1、首先在Thinkphp5的应用配置文件application/config.php下修改cookie配置项,让二级域名共享cookie

这个域名必须是主域名下的二级域名

//在cookie选项加入domain,配置域名
'cookie' => [
    // cookie 有效域名
    'domain'    => 'api.example.com',
],

2、服务器端响应头配置

将响应头设置成Access-Control-Allow-Origin:域名
响应头设置Access-Control-Allow-Credentials:true,表示跨域时,允许cookie添加到请求中。
注:设置Access-Control-Allow-Credentials:true后,要将Access-Control-Allow-Origin指定到具体的域,否则cookie不会带到客户端。

header('Access-Control-Allow-Origin:http://api.example.com');//允许单个域名
header('Access-Control-Allow-Credentials: true');//支持cookie跨域

3、Vue中axios请求配置

在main.js中配置axios

axios.defaults.withCredentials = true;//让ajax携带cookie

如果不在这个里面的话,可以搜索其他文件 axios.create ,一般是创建的时候配置,例如vue-element-admin里面是在这个文件:src/utils/request.js

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

juqery中这样写:

$.ajax({
  type: "post",
  url: "http://xxx/login.html",
  xhrFields: {
    withCredentials: true
  },
  crossDomain: true,
  data: {

  },
  dataType: "json",
  success: function (response) {
    console.log('response: ', response);
    
  }
});

4.修改vue文件的host,让域名可以正常访问

修改devServer或dev的配置(vue.config.js文件):

port:9528,
host:'api.example.com',
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

写代码的猫叔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值