Full project address: vuE3-element-plus
Experience address: http://8.135.1.141/vue3-admin-plus
Series entry:
- True fragrance law! Take you to use vuE3 + VITE2 to lift backstage (entrance)
preface
This article focuses on how to use and configure AXIOS in the architecture. The architecture rewraps AXIOS, using the request and response interceptors in AXIOS, cancelling requests, and so on. Let’s introduce it in detail
Axios official documentation
Related,
"axios": "0.21.3"
Copy the code
Introduction to core Files
utils/axiosReq.js
import store from '@/store'
import axios from 'axios'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { getToken, setToken } from '@/utils/auth'
// Used to save the request configuration
let reqConfig
// Used to save the loading ID in Element so that loading can be turned off in response
let loadingE
// Create an axios request instance with axios.create()
const service = axios.create()
// Axios intercepts before the request
// request
service.interceptors.request.use(
(req) = > {
// Axios cancels the request configuration
//axios cancel req https://www.jianshu.com/p/49568b10b29b
req.cancelToken = new axios.CancelToken((cancel) = > {
window.__axiosPromiseArr.push({
url: req.url,
cancel
})
})
// Set the token to the request header
// token setting
req.headers['AUTHORIZE_TOKEN'] = getToken()
// When downloading the file: set the response type to BLOb
/* download file*/
if (req.isDownLoadFile) {
req.responseType = 'blob'
}
// Request header content-type: 'multipart/form-data'
/* upload file*/
if (req.isUploadFile) {
req.headers['Content-Type'] = 'multipart/form-data'
}
// Whether loading loading is required before the request: bfLoading: true Yes
if (req.bfLoading) {
loadingE = ElLoading.service({
lock: true.text: 'Data loading'.// spinner: 'el-icon-loading',
background: 'rgba (0, 0, 0, 0.1)'})}/* Axios will concatenate the request's JSON parameter to the URL, such as "a=1&b=2" * */
if (req.isParams) {
req.params = req.data
req.data = {}
}
// Save the set request parameters for future use
//save req for res to using
reqConfig = req
return req
},
(err) = > {
Reject if the request fails to be sent
Promise.reject(err)
}
)
// Axios intercepts after the request
//response
service.interceptors.response.use(
(res) = > {
// Stop loading after request ->afHLoading is true and stop loading if there is a loadingE Id
if (reqConfig.afHLoading && loadingE) {
loadingE.close()
}
// If the file is downloaded, return it directly
// direct return, when download file
if (reqConfig.isDownLoadFile) {
return res.data
}
const { flag, msg, code, isNeedUpdateToken, updateToken } = res.data
// If isNeedUpdateToken is true, update token
if (isNeedUpdateToken) {
setToken(updateToken)
}
// Define success codes 0,200 and 20000 as success codes. You can add them if necessary
const successCode = '0200200'
if (successCode.indexOf(code)) {
// The service is successfully processed
return res.data
} else {
// Service failure processing
//403 No login, go to the login process again
if (code === 403) {
ElMessageBox.confirm('Please log in again', {
confirmButtonText: 'Log in again'.cancelButtonText: 'cancel'.type: 'warning'
}).then(() = > {
// Resets token, reload the page
store.dispatch('user/resetToken').then(() = > {
location.reload()
})
})
}
// Whether an error message isAlertErrorMsg:true is required
if (reqConfig.isAlertErrorMsg) {
ElMessage({
message: msg,
type: 'error'.duration: 2 * 1000})}// Return an error message
// If there is no catch, go unhandledrejection
return Promise.reject(res.data)
}
},
(err) = > {
/ / close the loading
if (loadingE) loadingE.close()
// Error message
ElMessage({
message: err,
type: 'error'.duration: 2 * 1000
})
/* HTTP error handling, handling across domains, 404,401,500 */
// Cross-domain error:Network error
let errObj = {
// Get the requested error message
msg: err.toString(),
// Request URL collection
reqUrl: reqConfig.baseURL + reqConfig.url,
// Request parameter collection
params: reqConfig.isParams ? reqConfig.params : reqConfig.data
}
// If a. Catch is not used for error capture, an unhandledrejection will be performed
return Promise.reject(JSON.stringify(errObj))
}
)
// Export the axios instance for the page to use
export default function axiosReq({ url, data, method, isParams, bfLoading, afHLoading, isUploadFile, isDownLoadFile, baseURL, timeout, isAlertErrorMsg }) {
return service({
// The total request url is: baseURL+url
url: url,
// Request method, default get
method: method ?? 'get'.// Json data before the request
data: data ?? {},
// Whether to concatenate parameters to the URL. Default is false
isParams: isParams ?? false.// Whether to load before a request. The default value is true
bfLoading: bfLoading ?? true.// Whether to disable loading after a request. The default value is true
afHLoading: afHLoading ?? true.// Whether to upload files. If the value is set to true when uploading files, the configuration related to uploading files will be set before the request
isUploadFile: isUploadFile ?? false.// Whether to download files. If this parameter is set to true, the configuration related to the downloaded files will be set before the request
isDownLoadFile: isDownLoadFile ?? false.// Whether error messages need to be displayed. If the value is set to false, error messages are not altered
isAlertErrorMsg: isAlertErrorMsg ?? true.// Set the basic url. The default value is the VITE_APP_BASE_URL attribute configured for. Env.x
baseURL: baseURL ?? import.meta.env.VITE_APP_BASE_URL,
// Set the default timeout period. The default timeout period is 15 seconds
timeout: timeout ?? 15000})}Copy the code
How to use
The first kind of
import axiosReq from "@/utils/axiosReq";
axiosReq({
baseURL: 'http://8.135.1.141/micro-service-test'.url: '/ty-user/brand/updateBy'.data: { id: 'fai'}, the timeout:1000.method: 'put'.isParams: true.bfLoading: true, isAlertErrorMsg:true
})
.then((res) = > {})
.catch((err) = > {})
Copy the code
The second,
Because the main. Js configuration is abstracted//global mount moment-mini
//import axios req
import axiosReq from '@/utils/axiosReq'App. Config. GlobalProperties $axiosReq = axiosReq so you can use itimport {getCurrentInstance} from 'vue'
let { proxy } = getCurrentInstance()
proxy.$axiosReq({
url: '/ty-user/brand/updateBy'.data: { id: 'fai'}, the timeout:1000.method: 'put'.isParams: true.bfLoading: true, isAlertErrorMsg:true
})
.then((res) = > {})
.catch((err) = > {})
Copy the code
Axios cancels the request
There are times in the business when requirements are cancelled, requests being sent, etc. Let’s talk about how Axios can gracefully cancel requests
Axios cancels the request to experience the address
How to configure
main.js
//axios cancel req
window.__axiosPromiseArr = []
Copy the code
utils/axiosReq.js
//axios cancel req https://www.jianshu.com/p/49568b10b29b
req.cancelToken = new axios.CancelToken((cancel) = > {
//__axiosPromiseArr Collects request addresses
window.__axiosPromiseArr.push({
url: req.url,
cancel
})
})
Copy the code
To summarize, define an __axiosPromiseArr global variable that collects the AXIOS request URL and then mounts it to the window
How to use
views/crud/ImgAddressPacking.vue
const cancelReq = () = > {
//cancel all req when page switch
if (window.__axiosPromiseArr) {
window.__axiosPromiseArr.forEach((ele, ind) = > {
ele.cancel()
delete window.__axiosPromiseArr[ind]
})
}
}
Copy the code