cli axios请求方式及跨域处理问题(2)

发送post请求时一般都要设置Content-Type,发送内容的类型,application/json指发送json对象但是要提前stringify一下。application/xxxx-form指发送?a=b&c=d格式,可以用qs的方法格式化一下,qs在安装axios后会自动安装,只需要组件里import一下即可。

const postData=JSON.stringify(this.formCustomer); 'Content-Type':'application/json'} const postData=Qs.stringify(this.formCustomer);//过滤成?&=格式 'Content-Type':'application/xxxx-form'}

1.拦截器的使用

当我们访问某个地址页面时,有时会要求我们重新登录后再访问该页面,也就是身份认证失效了,如token丢失了,或者是token依然存在本地,但是却失效了,所以单单判断本地有没有token值不能解决问题。此时请求时服务器返回的是401错误,授权出错,也就是没有权利访问该页面。

我们可以在发送所有请求之前和操作服务器响应数据之前对这种情况过滤。

// http request 请求拦截器,有token值则配置上token值 axios.interceptors.request.use( config => { if (token) { // 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了 config.headers.Authorization = token; } return config; }, err => { return Promise.reject(err); }); // http response 服务器响应拦截器,这里拦截401错误,并重新跳入登页重新获取token axios.interceptors.response.use( response => { return response; }, error => { if (error.response) { switch (error.response.status) { case 401: // 这里写清除token的代码 router.replace({ path: 'login', query: {redirect: router.currentRoute.fullPath} //登录成功后跳入浏览的当前页面 }) } } return Promise.reject(error.response.data) });

下面看下

vue cli脚手架前端调后端数据接口时候的本地代理跨域问题,如我在本地localhost访问接口:3002/是要跨域的,相当于浏览器设置了一到门槛,会报错XMLHTTPRequest can not load :3002/. Response to preflight request doesn't

pass access control…. 为什么跨域同源非同源自己去查吧,在webpack配置一下proxyTable就OK了,如下 config/index.js

dev: { 加入以下 proxyTable: { '/api': { target: 'https://40.00.100.100:3002/',//设置你调用的接口域名和端口号 别忘了加http changeOrigin: true, pathRewrite: { '^/api': 'https://www.jb51.net/' //这里理解成用‘/api'代替target里面的地址, 后面组件中我们掉接口时直接用api代替 比如我要调 用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add'即可 } } }

总结

以上所述是小编给大家介绍的vue-cli axios请求方式及跨域处理问题,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/pxdgj.html