1、首先,安装axios
npm install axios
2、自定义request.js文件
import axios from 'axios'
// 环境的切换
if (process.env.NODE_ENV === 'development') {
axios.defaults.baseURL = process.env.VUE_APP_SERVER_URL //开发环境
} else if (process.env.NODE_ENV === 'debug') {
axios.defaults.baseURL = '' // 调试环境
} else if (process.env.NODE_ENV === 'production') {
axios.defaults.baseURL = process.env.VUE_APP_SERVER_URL // 生产环境
}
axios.defaults.timeout = 100000
axios.defaults.headers['Content-Type'] = 'application/json' // 设置默认提交json
axios.interceptors.request.use(
(config) => {
config.headers = {
'Accept': '*/*'
}
return config
},
(error) => {
return Promise.error(error)
})
axios.interceptors.response.use(
// 请求成功
(res) => (res.status === 200 ? Promise.resolve(res) : Promise.reject(res)),
// 请求失败
(error) => {
if (error.response) {
if (error.response.status === 401) {
//
} else {
return Promise.reject(error.response)
}
} else {
return Promise.reject(error.response)
}
})
// 封装xiaos请求 封装axios里的get
export function axiosGet(url, params) {
if (url !== '/premin/aaa') { //有关权限接口
if (window.myLeftMenuList.token) {
params.token = window.myLeftMenuList.token
}
}
return new Promise(
(resolve, reject) => {
axios.get(url, { params: params })
.then((res) => {
resolve(res.data)
})
.catch((err) => {
reject(err.data)
})
}
)
}
// 封装xiaos请求 封装axios里的post
export function axiosPost(url, data) {
let newUrl
if (window.myLeftMenuList.token) {
newUrl = `${url}?token=${window.myLeftMenuList.token}`
} else {
newUrl = url
}
return new Promise(
(resolve, reject) => {
axios.post(newUrl, data)
.then((res) => {
resolve(res.data)
})
.catch((err) => {
reject(err.data)
})
}
)
}
// 封装xiaos请求 封装axios里的put
export function axiosPut(url, data) {
return new Promise(
(resolve, reject) => {
axios.put(url, JSON.stringify(data))
.then((res) => {
resolve(res.data)
})
.catch((err) => {
reject(err.data)
})
}
)
}
// 封装xiaos请求 封装axios里的delete
export function axiosDelete(url, data) {
return new Promise(
(resolve, reject) => {
axios.delete(url, { params: data })
.then((res) => {
resolve(res.data)
})
.catch((err) => {
reject(err.data)
})
}
)
}
3、src目录下新建api文件夹,api下新建index.js文件,api新建innerApi文件夹,innerApi下新建index.js文件
//api下index.js
const TEST = '/test/api',
export default {
TEST
}
//innerApi下index.js
import { axiosGet, axiosPost } from '../../utils/request.js'
import API from '@/api/index.js'
// 按照格式确定方法名
const getTest1 = (data) => axiosGet(`${API.TEST}/user/open/aa`, data),
getTest2 = (data) => axiosPost(`${API.TEST}/testaa/bb`, data),
export {
getTest1 , getTest2
}
//其他页面引入
import { getTest1, getTest2 } from '@/api/innerApi/index.js'