安装axios
yarn add axios
npm i axios --save
创建目录
一般在/src/assets/ 目录下创建js 目录,新建request.js 文件
封装axios拦截器
request.js
import axios from 'axios'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const service = axios.create({
baseURL: "http://your.server.host:11231",
timeout: 15000
})
service.interceptors.request.use(
config => {
return config
},
error => {
console.log(error)
return Promise.reject(error)
}
)
service.interceptors.response.use(
response => {
const res = response.data
if (res.status === -1) {
} else if (res.status === -2) {
return Promise.reject(new Error(res.msg || 'Error'))
} else {
return res
}
},
error => {
return Promise.reject(error)
}
)
const api = {
getXXX: (data) => service({
url: '/api/v2/XXXXXX',
method: 'get',
params: data
}),
setXXX: (data) => service({
url: '/api/v2/XXXXXX',
method: 'post',
data
}),
}
export default api
注释的部分为项目中实用的一些功能,有elementui的提示框,有vant的Toast等。还有用js-cookie的Token认证,选择打开注释就可以了
api使用
main.js 里全局引用
import api from './assets/js/request'
Vue.prototype.$api = api
xxx.vue 里调用API
GET
async OnXxxxxxx() {
let res = await this.$api.getXXX({
sn: this.sn,
num: this.num,
})
let res = await this.$api.getXXX()
if (res.status == 1) {
} else {
Toast(res.msg)
}
},
POST
async Commit() {
let res = await this.$api.setXXX({
type: this.type,
priority: this.priority,
title: this.title,
message: this.message,
contact: this.contact,
})
if (res.status == 1) {
}
},
|