此版本封装主要是对请求封装,拦截什么的没做处理。主要是处理了请求的方式是post还是get请求做了处理,新建一个http.js,代码如下:
import Qs from 'qs' import axios from "axios" axios.defaults.timeout = 15000; axios.defaults.transformResponse = [function (data) { data = JSON.parse(data) return data }] axios.interceptors.request.use(function(config) { console.log("请求开始") return config; }, function (error) { return Promise.reject(error); }); axios.interceptors.response.use((res) => { console.log("请求结束 ") return res; }, (error) => { return Promise.reject(error); }); function http(type,url, params,contentType) { let contType = contentType=='json' ? 'application/json':'application/x-www-form-urlencoded' let paramstranform = contentType == 'json' ? params : Qs.stringify(params) if(type == "get"){ return new Promise((resolve, reject) => { // alert("axios-token:::"+localStorage.token) axios({ method:'get', url:url, headers: {'token' : localStorage.token}, params:params }) // axios.get(url, { params: params },{headers : {'token' : localStorage.token}}) .then((res) => { resolve(res.data) }).catch(err => { if (err == "Error: timeout of 15000ms exceeded") { console.log("服务器请求超时") return } alert(err) }) }) }else{ return new Promise((resolve,reject)=>{ axios({ method:'post', url:url, headers: {'Content-Type': contType}, data:paramstranform }) // axios.post(url,paramstranform,{headers:{'Content-Type': contType,'token' : localStorage.token}}) .then((res)=>{ resolve(res.data) }).catch(err=>{ if(err == "Error: timeout of 15000ms exceeded"){ alert("服务器请求超时,请刷新页面重新进入") } alert(err) }) }) } } export default http
在在main.js里引用
import httpRequest from '@/config/http' 具体的地址还有文件名自己改写 Vue.prototype.$http = httpRequest //定义一个全局变量
在文件或者模板文件里运用如下;
getList(){ this.$http('post',this.baseUrl+'/tag/theme/list').then((res) => { console.log(res) }); }