创建一个request.js用于封装axios,在 src/api/request,设置拦截器统一处理请求和相应。
封装 axios:request.js:
import axios from 'axios'
import {Message, Loading} from "element-ui"
import {getToken} from "@/utils/auth"
function Index({...config}) {
// create an axios instance
const service = axios.create({
/*headers: {
'Cache-Control': 'no-cache'
},*/
baseURL: config.baseURL || process.env.VUE_APP_BASE_API, // url = base url + request url
// withCredentials: true, // send cookies when cross-domain requests
timeout: 30000 // request timeout
})
// request interceptor
service.interceptors.request.use(
config => {
return config
},
error => {
return Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
response => {
return response
},
error => {
const {request = {}} = error;
const {status, response} = request;
error.status = status
try {
error.res = JSON.parse(response)
} catch (e) {
console.warn(e)
}
return Promise.reject(error)
}
)
/**
* 发起请求
* @param method 请求方法
* @param url 请求地址
* @param params 要发送的数据
* @param config 配置
* @param axiosConfig Axios配置项
* @returns {Promise<never>|Promise<AxiosResponse<T>>}
*/
const requestProcessor = (method, url, params, config, axiosConfig) => {
const headers = {}
const token = getToken().token
if (token) {
// let each request carry token
headers['Authorization'] = 'JWT ' + token
}
if (config.formData) {
const fd = new FormData();
for (let key in params) {
fd.append(key, params[key])
}
params = fd
}
switch (method.toUpperCase()) {
case 'GET':
return service.get(url, {
params,
headers,
...axiosConfig,
})
case 'POST':
return service.post(url, params, {
headers,
...axiosConfig,
})
case 'DELETE':
return service.delete(url, {
params,
headers,
...axiosConfig,
})
case 'PUT':
return service.put(url, params, {
headers,
...axiosConfig,
})
default:
return Promise.reject(new Error(`${method} 方法无效,请用正确的请求方法`))
}
}
this.service = async ({method, url, params, config = {}, axiosConfig = {}}) => {
const {isLoading = true, isToast = true} = config
let loadingInstance
isLoading && (loadingInstance = Loading.service({
fullscreen: true,
background: 'transparent',
text: '加载中...'
}))
try {
const response = await requestProcessor(method, url, params, config, axiosConfig)
// 此处可以再次拦截
return response.data
} catch (error) {
isToast && Message.error(error.message)
throw error
} finally {
isLoading && loadingInstance.close()
}
}
}
export const {request} = new Index()
export default Index
接口 listing.js:
import Request from "@/api/request"
const {service} = new Request()
export default {
userPostList({pageSize, page}) {
return service({
method: 'get',
url: '/userpostlist/',
params: {
pageSize,
page
},
config: {
isLoading: false
}
})
}
}
在 Vue 组件中使用:
import listing from "@/api/listing"
export default {
mounted() {
this.getList()
},
methods: {
getList() {
this.isLoading = true
listing.userPostList({
pageSize: this.pageSize,
page: this.currentPage,
}).then(data => {
this.currentPage = parseInt(data.currentPage)
this.total = data.total
this.list = data.results
}).finally(() => {
this.isLoading = false
})
}
}
}
2.async await 封装
import axios from 'axios';
import QS from 'qs'
axios.defaults.timeout = 5000;
axios.defaults.baseURL ='http://192.168.0.xxx:xxxx'; //填写域名
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.interceptors.request.use(
config => {
let token = sessionStorage.getItem('token');
console.log(token)
if(token){
config.headers.Authorization = 'bearer ' + token;
}
return config;
},
error => {
return Promise.reject(err);
}
);
//响应拦截器即异常处理
axios.interceptors.response.use(response => {
return response
}, err => {
if (err && err.response) {
switch (err.response.status) {
case 400:
console.log('错误请求')
break;
case 401:
console.log('未授权,请重新登录')
break;
case 403:
console.log('拒绝访问')
break;
case 404:
console.log('请求错误,未找到该资源')
break;
case 405:
console.log('请求方法未允许')
break;
case 408:
console.log('请求超时')
break;
case 500:
console.log('服务器端出错')
break;
case 501:
console.log('网络未实现')
break;
case 502:
console.log('网络错误')
break;
case 503:
console.log('服务不可用')
break;
case 504:
console.log('网络超时')
break;
case 505:
console.log('http版本不支持该请求')
break;
default:
console.log(`连接错误${err.response.status}`)
}
} else {
console.log('连接到服务器失败')
}
return Promise.resolve(err.response)
})
const api = {
async get (url, data) {
try {
let res = await axios.get(url, {params: data})
res = res.data
return new Promise((resolve) => {
if (res.code === 0) {
resolve(res)
} else {
reject(res)
}
})
} catch (err) {
alert('服务器出错')
console.log(err)
}
},
async post (url, data) {
try {
let res = await axios.post(url, QS.stringify(data))
res = res.data
return new Promise((resolve, reject) => {
if (res.code === 0) {
resolve(res)
} else {
reject(res)
}
})
} catch (err) {
// return (e.message)
alert('服务器出错')
console.log(err)
}
},
}
export { api }
在组件中引用require.js
import {api} from '../api/request.js'
async login(){
let param={
username:'admin',
password:111111
}
let {data} = await api.post('url',param)
console.log(data)
sessionStorage['token'] = data.token;
},
async aside(){
let {data} = await api.get('url',{
articleId:640,
})
console.log(data)
},