axios的封装,不仅限于vue使用
程序员文章站
2022-06-23 16:39:32
axios.js封装import axios from 'axios'// 创建axios实例let baseURL = process.env.VUE_APP_API_HOST// /dev本地的代理规则if (process.env.NODE_ENV == 'development') {baseURL = '/dev'}const service = axios.create({//baseURL: process.env.VUE_APP_API_HOST, // api的bas...
axios.js封装
import axios from 'axios'
// 创建axios实例
let baseURL = process.env.VUE_APP_API_HOST
// /dev本地的代理规则
if (process.env.NODE_ENV == 'development') {
baseURL = '/dev'
}
const service = axios.create({
//baseURL: process.env.VUE_APP_API_HOST, // api的base_url
baseURL: baseURL,
timeout: 5000 // 请求超时时间
})
// request拦截器
service.interceptors.request.use(config => {
// Do something before request is sent
// if (store.getters.token) {
// // config.headers['X-Token'] = getToken() // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
// }
return config
}, error => {
// Do something with request error
Promise.reject(error)
})
// respone拦截器
service.interceptors.response.use(
response => {
// const res = response.data
return response
},
error => {
return Promise.reject(error)
})
export default service
api.js统一管理
import request from '@/utils/request'
export function get(params) {
return request({
url: 'url',
method: 'get',
params
})
}
export function get(data) {
return request({
url: 'url',
method: 'post',
data
})
}
页面里使用
import {get,post} from '@/utils/request'
get(obj).then()
post(obj).then()
本文地址:https://blog.csdn.net/fxg1997/article/details/110630511