1.安装并引入
yarn add axios
import axios from 'axios' //在js文件中引入
2.配置
axios.defaults.timeout = 5000
axios.defaults.baseURL = 'http://localhost:8080'
axios.defaults.withCredentials = true
3.请求拦截与响应拦截
// 请求拦截
axios.interceptors.request.use(
config => {
// 配置通用参数
return config
},
err => {
return Promise.reject(err)
}
)
// 响应拦截
axios.interceptors.response.use(
response => {
if (response) {
// 响应处理
}
return response
},
error => {
return Promise.reject(error.response.data)
}
)
4.封装get post put delete请求
/**
* get请求
* @param url
* @param params
* @returns {Promise}
*/
const get = (url, params) => {
return new Promise(async (resolve, reject) => {
try {
const res = await axios.get(url, {
params: params
})
resolve(res)
} catch (err) {
reject(err)
}
})
}
/**
* post请求
* @param url
* @param params
* @returns {Promise}
*/
const post = (url, params) => {
return new Promise(async (resolve, reject) => {
try {
const res = await axios.post(url, params)
resolve(res)
} catch (err) {
reject(err)
}
})
}
/**
* put请求
* @param url
* @param params
* @returns {Promise}
*/
const put = (url, params) => {
return new Promise(async (resolve, reject) => {
try {
const res = await axios.put(url, params)
resolve(res)
} catch (err) {
reject(err)
}
})
}
/**
* delete请求
* @param url
* @param params
* @returns {Promise}
*/
const del = (url, params) => {
return new Promise(async (resolve, reject) => {
try {
const res = await axios.delete(url, {
data: params
})
resolve(res)
} catch (err) {
reject(err)
}
})
}
5.导出
export default {
get,
post,
put,
del
}