1 Introduction
A friend who just graduated has little experience in projects, and always uses axios to send requests by mistake. He spends all day asking around in the company, which leads to slow progress of the project, so here I share the axios package used in my own project.
2. Install axios and basic use
// 安装
npm install axios -s
// 引入
import axios from 'axios'
// 使用
axios({
method: "GET",
url: "http://localhost:3000/api/getData"
}).then(response => {
console.log(response);
})
axios({
method: "POST",
url: "http://localhost:3000/api/postData",
data:{name:"xiaoming",age:18,params:"提交的数据。。。"}
}).then(response => {
console.log(response);
})
The above simply shows how to use get to obtain data and submit data through post. Of course, the same is true for put and delete, so I won’t show too much. Axios directly returns a promise, so the data returned by the backend service can be received directly in then. The following shows the specific parameters of the response object.
3. Encapsulate axios
The essence of encapsulation is to reduce code duplication and extract reusable parts, while axios encapsulation is based on interceptors, and performs corresponding operations on requests and responses
The request interceptor is to do some unified processing before the request is sent, such as doing some operations on the request header, different processing for different methods, etc.
// request拦截器
service.interceptors.request.use(
(config) => {
// config.headers["Sec-Fetch-Dest"] = "image"
// JWT鉴权处理
if (store.getters['user/token']) {
config.headers['Token'] = store.state.user.token
}
// 处理get请求
if (config.method=='get') {
// 在这里对get请求进行包装,比如传参数,比如参数加密或者携带默认参数
}
return config
},
(error) => {
return Promise.reject(error)
}
)
The response interceptor is to perform certain operations on the response body of the server after the request is sent successfully. The code here is mainly to uniformly process various states
// response拦截器
service.interceptors.response.use(
(response) => {
if (response.status == 200) {
const res = response.data
if (res.code == 200) {
return res
} else if (res.code == 401 || res.code == 403) {
store.dispatch('user/loginOut')
showError(res)
return Promise.reject(res)
}else {
showError(res)
return Promise.reject(res)
}
} else {
ElMessage({
message: '网络连接失败,请检查网络情况',
type: 'error',
})
return Promise.reject(res)
}
},
(error) => {
const badMessage = error.message || error
showError({ code:999, message: badMessage })
return Promise.reject(error)
}
)
Then in the project, all the APIs are centralized in one place for management, and then introduced to the page when needed
import { get, post, del, edit } from "@/utils/system/request"
export const user = {
list: (data) => get('/sys/user/list', data),
del: (data) => post('/sys/user/delete', data),
info: (data) => get('/sys/user/info/' + data),
save: (data) => post('/sys/user/save', data),
update: (data) => post('/sys/user/update', data),
}
import { user } from "@/api/sys"
const getUserList = async () => {
let { code, data } = await user.list()
userList.value = code == 200 ? data.list : []
}
At this point, a request call has been successfully completed!