抱歉,您的浏览器无法访问本站

本页面需要浏览器支持(启用)JavaScript


了解详情 >

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',

评论