请问一下 ajax 跨域访问cookie丢失问题
粉丝福利 : 关注VUE中文社区公众号,回复视频领取粉丝福利
技术栈采用vue+vuex+axios,后端是express 前端请求代码:
import axios from 'axios'
// let base = ' https://cnodejs.org/api/v1'
let base = 'http://localhost:2000'
// let base = 'https://wx.xuminjun.com'
// 自动将响应头中的token 放到请求头中去请求
// axios.defaults.withCredentials = true
axios.create({
timeout: 1000,
withCredentials: true
})
// 登录接口
export const login = params => {
return axios.post(base + '/api/login', params)
.then(res => {
console.log(res)
return res.data
})
.catch(error => { console.log(error) })
}
// 获取nodejs资讯
export const getTopics = params => { return axios.post(base + '/api/test').then(res => res.data).catch(error => { console.log(error) }) }
// 获取用户信息
export const getUser = params => { return axios.get('/getUser', {params: params}).then(res => res.data).catch((error) => { console.log(error) }) }
// 获取左侧菜单列表
export const getMenus = params => { return axios.get('/getMenus').then(res => res.data).catch(error => { console.log(error) }) }
后端代码 app.js
// 允许跨域请求
app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild, x-access-token');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
res.header('Access-Control-Allow-Credentials', 'true');
if (req.method == 'OPTIONS') {
res.send(200); /让options请求快速返回/
}
else {
next();
}
});
结果显示: 登录结果返回时 响应头带cookie 再次去服务器请求是 cookie请求头 丢失
请求各位大神解惑