做项目的时候,api接口统一管理,一边学习一边记录
一、安装axios
npm install axios
二、 在 src 目录下新建 api 文件夹
api文件夹下存放项目接口文件,以便统一管理
在 api 文件夹下 新建 index.js
三、引入并封装
index.js
1. 引入 axios
import axios from 'axios'
2. 环境的切换
// 环境的切换
if (process.env.NODE_ENV === 'development') {
axios.defaults.baseURL = ''
} else if (process.env.NODE_ENV === 'debug') {
axios.defaults.baseURL = ''
} else if (process.env.NODE_ENV === 'production') {
axios.defaults.baseURL = ''
}
3. 设置请求超时、POST 请求头
// 设置请求超时
axios.defaults.timeout = 10000
// 设置 POST 请求头
axios.defaults.headers.post['Content-Type'] = 'application/json'
4. 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
config.headers.Authorization = window.sessionStorage.getItem('token')
// 在最后必须 return config
return config
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error)
})
5. 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error)
})
6. 添加通用方法
export const POST = (url, params, config = {}) => {
return axios.post(url, params, config).then(res => res.data)
}
export const GET = (url, params) => {
return axios.get(url, { params: params }).then(res => res.data)
}
export const ALL = (promiseArr) => {
return axios.all(promiseArr)
}
四、封装接口
1. 在 api 文件夹下 新建 list.js (按自己需求新建文件)
import * as API from './'
export default {
// 获取省
apiProvincesList: params => {
return API.GET('wechat/v1.0/pois/provinces', params)
},
// 获取市
apiCitiesList: params => {
const provinceId = params
return API.GET(`wechat/v1.0/pois/cities/${provinceId}`, params)
},
// 获取县/区
apiDistrictsList: params => {
const districtId = params
return API.GET(`wechat/v1.0/pois/districts/${districtId}`, params)
},
// 提交订单
apiAdd: params => {
const config = {
needFormData: true
}
return API.POST('wechat/v1.0/orders/add', params, config)
}
}
2. 在 vue 中使用
import API from 'api/list.js'
// 获取省
getProvincesList () {
API.apiProvincesList().then(res => {
if (res.resultCode === 0) {
this.province_list = res.data
// console.log(this.province_list)
} else {
this.$toast(res.resultInfo)
}
})
},
// 获取市
getCitiesList () {
const provinceId = this.provinceId
API.apiCitiesList(provinceId).then(res => {
if (res.resultCode === 0) {
this.city_list = res.data
// console.log(this.city_list)
} else {
this.$toast(res.resultInfo)
}
})
},
// 获取县/区
getDistrictsList () {
const districtId = this.districtId
API.apiDistrictsList(districtId).then(res => {
if (res.resultCode === 0) {
this.county_list = res.data
// console.log(this.county_list)
} else {
this.$toast(res.resultInfo)
}
})
},
//提交订单
const config = {
orderName: this.orderName, // 申请人姓名
orderPhone: this.orderPhone, // 申请人手机
...
}
// console.log(JSON.stringify(data))
API.apiAddPackage(config).then(res => {
if (res.resultCode === 0) {
this.$toast('申请成功!')
this.successDialog = true
} else {
this.$toast(res.resultInfo)
}
})