vue 和 tp5之间的跨域传输token问题
前言:
1.为什么使用token?
防止请求重复提交
2.vue 使用token交互时,token总验证失败? 为空?
thinkphp 的表单令牌token 在vue 前后端分离开发情景下,
由于浏览器同源策略下 出现跨域 ,但是我们都知道怎么处理一般情况下的跨域请求 但是token这块如果缺少配置会出现问题。
屁话不多说 开始上代码:(本文所有代码均在文章结尾处链接下载)
一.前端:(vue)
我们在页面渲染前 与后端服务器请求token 存入cookie
<script>
export default {
...
created:function(){
this.$post(
this.GLOBAL.host+'fileup/index/gettoken')
.then((response) => {
this.$util.cookies.set('token', response.token)
})
},
</script>
此处利用axios工具进行请求
设置跨域请求参数,请求拦截器,响应拦截器
import axios from 'axios';
import qs from 'qs';
import util from './util.js';
axios.defaults.timeout = 5000;
axios.defaults.baseURL ='';
axios.defaults.withCredentials=true; /
//http request 拦截器
axios.interceptors.request.use(
config => {
let token = util.cookies.get('token')
config.data = qs.stringify(config.data)
config.headers = {
'Content-Type':'application/x-www-form-urlencoded',
'token':token
}
return config;
},
error => {
return Promise.reject(err);
}
);
//http response 拦截器
axios.interceptors.response.use(
response => {
if(response.data.errCode ==2