vue结合php前后端分离项目如何允许cookie session跨域
很多童鞋会发现vue请求api接口的时候多个地址没法共享session,也就是session会丢失。我们知道session是基于cookie的,ajax请求没法共享session主要是因为cookie跨域引起的。cookie跨域如何解决呢?
php后端端
header('Content-Type: text/html; charset=utf-8');
$origin = $_SERVER['HTTP_ORIGIN'] ? $_SERVER['HTTP_ORIGIN'] :'*';
header("Access-Control-Allow-Origin: $origin");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
header('Access-Control-Max-Age: 1728000');
1、前端 vue ajax请求解决cookie跨域 vue-resource
this.$http.get('getlogin',{ credentials: true }).then(res => {
console.log(res)
})
this.$http.post('postlogin',{userInfo: $('.form-signin').serialize()},{ credentials: true }).then(res => {
console.log(res)
if(res.body.status != 200) {
console.log('登录失败')
}else {
console.log('登录成功')
}
})
2、原生js中ajax请求api cookie跨域
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.xxx.com/api');
xhr.withCredentials = true;
xhr.onload = onLoadHandler;
xhr.send()
3、jquery中ajax请求api cookie跨域
$.ajax({
url: "http://localhost:8080/orders",
type: "GET",
xhrFields: {
withCredentials: true
},
crossDomain: true,
success: function (data) {
render(data);
}
});
4.axios ajax请求api cookie跨域 (vue react angular通用)
const service = axios.create({
baseURL: process.env.BASE_API, // node环境的不同,对应不同的baseURL
timeout: 5000, // 请求的超时时间
//设置默认请求头,使post请求发送的是formdata格式数据// axios的header默认的Content-Type好像是'application/json;charset=UTF-8',我的项目都是用json格式传输,如果需要更改的话,可以用这种方式修改
// headers: {
// "Content-Type": "application/x-www-form-urlencoded"
// },
withCredentials: true // 允许携带cookie
})