axios封装一个通用的请求
程序员文章站
2022-07-02 15:34:44
...
import axios from 'axios'
axios.defaults.timeout = 5000
//http request 拦截器
axios.interceptors.request.use(
config => {
config.headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
'token': localStorage.getItem('token') // 获取token缓存
}
return config
},
error => {
return Promise.reject(error)
}
);
export default {
/**
* 封装get方法
* @param url
* @param data
* @returns {Promise}
*/
get: function (url, params = {}) {
return new Promise((resolve, reject) => {
axios.get(url, {
params: params
})
.then(response => {
resolve(response.data)
})
.catch(err => {
reject(err)
})
})
},
/**
* 封装post请求
* @param url
* @param data
* @returns {Promise}
*/
post: function (url, data) {
return new Promise((resolve, reject) => {
axios.post(url, data)
.then(response => {
resolve(response.data)
}, err => {
reject(err)
})
})
}
}
使用
vue中
直接导入import http from ‘http.js’
result = http.get(‘地址’, {参数}
推荐阅读