In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
This article focuses on "how to achieve the secondary encapsulation of axios in vue". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to achieve the secondary encapsulation of axios in vue.
Axios
Axios is a promise-based HTTP library that can be used in browsers and node.js.
It is also widely used in the front-end framework, whether it is vue or react, there are many projects that use axios as the network request library.
I have used axios in several recent projects and encapsulated a generic request service based on axios according to common business scenarios.
Npm:
$npm install axios
Bower:
$bower install axios
Using cdn:
Business scenario:
Global request configuration.
Promise encapsulation of requests such as get,post,put,delete.
Global request state management for loading animation, etc.
Route jump cancels the current page request.
The request carries token, and the permission errors are managed uniformly.
Default configuration
Define the global default configuration
Axios.defaults.timeout = 10000 / / time-out cancel request axios.defaults.headers.post ['Content-Type'] =' application/json;charset=UTF-8'axios.defaults.baseURL = process.env.BASE_URL
Custom configuration (see business scenarios, for introduction only)
/ / set the default value of the configuration var instance = axios.create when creating the instance ({baseURL: 'https://api.another.com'});// modify the default value instance.defaults.headers.common [' Authorization'] = AUTH_TOKEN after the instance has been created
Priority: custom configuration > default configuration
Request and response interceptor
Request interceptor
/ / request list const requestList = [] axios.interceptors.request.use ((config) = > {/ / 1. Add the currently requested URL to the request list array requestList.push (config.url) / / 2. To start the request, change the loading state for loading animation using store.dispatch ('changeGlobalState', {loading: true}) / / 3. Get token from store and add it to the request header for permission verification at the backend const token = store.getters.userInfo.token if (token) {config.headers.token = token} return config}, function (error) {return Promise.reject (error)})
1. The request interceptor adds all requested url to the request list variable to prepare for cancellation of the request and loading status management
two。 Once the request starts, you can turn on the animation loading effect.
3. After logging in, users can carry token in the request header for permission verification.
Response interceptor
Axios.interceptors.response.use (function (response) {/ / 1. Delete requestList.splice (requestList.findIndex (item = > item = response.config.url), 1) / / 2 from the request list in the current request. Change the loading status if (requestList.length = 0) {store.dispatch ('changeGlobalState', {loading: false})} / / 3 when the request list is empty. Unified processing authority authentication error management if (response.data.code = 900401) {window.ELEMENT.Message.error ('invalid authentication, please log in again!' 1000) router.push ('/ login')} return response}, function (error) {/ / 4. Process the cancellation request if (axios.isCancel (error)) {requestList.length = 0 store.dispatch ('changeGlobalState', {loading: false}) throw new axios.Cancel (' cancel request')} else {/ / 5. Failed to process network request window.ELEMENT.Message.error ('Network request failed', 1000)} return Promise.reject (error)})
1. Delete the corresponding request from the request list after the response is returned
two。 When the request list is empty, that is, all requests end, loading animation ends
3. Unified interception processing of authority authentication error report
4. The processing of the cancellation request needs to be combined with other code instructions
5. Since the backend of the project does not use RESTful-style interface requests, all but 200 are classified as network requests failed.
Promise encapsulation and cancellation request
Const CancelToken = axios.CancelToken//cancel token list let sources = [] const request = function (url, params, config, method) {return new Promise ((resolve, reject) = > {axios [method] (url, params, Object.assign ({}, config, {/ / 1). Create cancel token cancelToken: new CancelToken (function executor (c) {/ / 2.) by passing the executor function to the CancelToken constructor. Save cancel token in the list sources.push (c)}) .then (response = > {resolve (response.data)}, err = > {if (err.Cancel) {console.log (err)} else {reject (err)}}) .catch (err = > {reject (err)})} const post = (url, params, config = {}) = > {return request (url, params, config, 'post')} const get = (url, params) Config = {}) = > {return request (url, params, config, 'get')} / / 3. Export cancel token list for global routing guards to use export {sources, post, get}
1.axios cancel token API
two。 Save the request list that needs to be cancelled and export it to the navigation guard for use
3.router.js
.. import {sources} from'. / service/request'...router.beforeEach ((to, from, next) = > {document.title = to.meta.title | | cancel the current page network request sources.forEach (item = > {item ()}) sources.length = 0 next ()} when the to.name / / route changes.
Request.js complete code:
/ / introduce network request library https://github.com/axios/axiosimport axios from 'axios'import store from'.. / store'import router from'.. / router'// axios.defaults.timeout = 10000const requestList = [] axios.defaults.headers.post ['Content-Type'] =' application/json Charset=UTF-8'axios.defaults.baseURL = process.env.BASE_URL// Custom interceptor axios.interceptors.request.use ((config) = > {requestList.push (config.url) store.dispatch ('changeGlobalState', {loading: true}) const token = store.getters.userInfo.token if (token) {config.headers.token = token} return config} Function (error) {return Promise.reject (error)}) axios.interceptors.response.use (function (response) {requestList.splice (requestList.findIndex = > item = response.config.url), 1) if (requestList.length = 0) {store.dispatch ('changeGlobalState', {loading: false})} if (response.data.code = 900401) {window.$toast.error (' invalid certification Please log in again!' , 1000) router.push ('/ login')} return response}, function (error) {requestList.length = 0 store.dispatch ('changeGlobalState', {loading: false}) if (axios.isCancel (error)) {throw new axios.Cancel (' cancel request')} else {window.$toast.error ('Network request failed!' , 1000)} return Promise.reject (error)}) const CancelToken = axios.CancelTokenlet sources = [] const request = function (url, params, config, method) {return new Promise ((resolve, reject) = > {axios [method] (url, params, Object.assign (config, {cancelToken: new CancelToken (function executor (c) {sources.push (c)})) .then (response = > {resolve (response.data)}) Err = > {reject (err)}) .catch (err = > {reject (err)})} const post = (url, params, config = {}) = > {return request (url, params, config, 'post')} const get = (url, params, config = {}) = > {return request (url, params, config,' get')} export {sources, post, get} I believe you have a deeper understanding of "how to achieve the secondary encapsulation of axios in vue", so you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.