vue axios
Vue-resource已经不维护了,现在axios已经成为vue的标配
//全局 拦截器 // 拦截器一般做什么? // // 1. 修改请求头的一些配置项 // 2. 给请求的过程添加loadin // 3. 给请求添加参数 // 4. 权限验证 this.$axios.create({ // headers: { // 'content-type': 'application/json; charset=utf-8' // }, baseURL: '/api', // url = base url + request url //timeout: 10000 // request timeout }) this.$axios.interceptors.request.use(config=>{ console.log(config); config.headers.xx='11' //根据post和get请求传公共参数 if(config.method === 'post') { let data = Qs.parse(config.data) //将aa=11&bb=22转{aa=11,bb=22} config.data = Qs.stringify({ //赋值给结构是 aa=11&bb=22 cmsId: JSON.parse(localStorage.getItem('uesrinfo')).id, ...data }) if( !(/cmsId/ig.test(config.url)) ){ config.params = { cmsId: JSON.parse(localStorage.getItem('uesrinfo')).id, ...config.params } } } else if(config.method === 'get') { if( !(/cmsId/ig.test(config.url)) ){ config.params = { cmsId: JSON.parse(localStorage.getItem('uesrinfo')).id, ...config.params } } } return config },err=>{ console.log(err) }) // 响应拦截器 this.$axios.interceptors.response.use((response) => { if(response.config.method == 'post'){ Loading.service().close(); //接口请求完成后关闭loading } return response }, (error) => { Loading.service().close(); return Promise.reject(error) }) this.$axios({ method: 'post', url: 'www.xgllseo.com/', //如果url参数带有http、https则没效果,否则就会是http://www.baidu.com+url的路径 baseURL:'http://www.baidu.com', //只有get时才有效,http://xxx/com/1?id=12345 params: {ID: 12345}, //只有put/post/patch请求类型时,请求体才能传数据给后台, // 且数据类型只能是FormData(类似input里面的数据), File(类似选中的图片、rar等), Blob(类似视频、音频) data: { firstName: 'Fred', lastName: 'Flintstone' }, //设置返回给浏览器的是什么数据类型 // 可选项 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // 默认值是json, //请求头用来传token居多 headers: {'Content-Type': 'application/json'}, //可以理解为局部拦截器,在全局的拦截器中加了我们不需要的字段,可以在此处再次编辑 transformRequest: (data, headers) => { delete headers.common.AUTHORIZATION //例如删除了 request.headers.common={AUTHORIZATION:'xxx'} return data }, //拦截器,选项允许我们在数据传送到`then/catch`方法之前对数据进行改动 transformResponse: [function (data) { // Do whatever you want to transform the data return data; }] }).then(function(response){ console.log(response); }).catch(function(err){ console.log(err); });;
axios中x-www-form-urlencoded格式提交post请求
axios({ url: `xxxx`, method: 'post', data, // 利用 transformRequest 进行转换配置 transformRequest: [ function(oldData) { // console.log(oldData) let newStr = ''; for (let item in oldData) { newStr += encodeURIComponent(item) + '=' + encodeURIComponent(oldData[item]) + '&'; } newStr = newStr.slice(0, -1); return newStr; } ], headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
参考https://www.jianshu.com/p/7a9fbcbb1114
如果遇到跨域问题,请使用代理https://sdeno.com/?p=7834
要么然后台加一个请求头。https://sdeno.com/?p=4815