In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Encapsulating the operation method of axios in the vue project, I believe that many inexperienced people do not know what to do about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
Preface
I often encounter axios when learning and doing projects. Previous projects are usually configured with axios, so I always have a general impression. Recently, I have an opportunity to manually configure axios, record and share it.
Benefits of axios encapsulation
The advantage of axios package is unified processing, improved efficiency and easy maintenance.
You can use the axios request interface as follows
Axios.get ('http://localhost:10086/user?ID=12345'). Then (response = > {/ / successful operation.}) .catch (error = > {/ / failed operation.})
But when there are more interface requests and more requirements, write such code in every place in the project where the interface request is needed, which will produce a lot of repetitive code, reduce our development efficiency and improve maintenance costs.
Encapsulation idea
We need to configure axios centrally at once to adapt the configuration to most of the scenarios of our project. We can create a new js file, create a new axios instance with custom configuration, and then make a basic configuration of the instance, add some processing we need before the request (processing the request body), after the request (processing the returned result), and then export it for use.
Priority of configuration
Configurations are merged in a priority order. The order is the default value of the library found in lib/defaults.js, then the defaults property of the instance, and finally the config parameter of the request. (in this way, we can deal with some special situations separately.)
The lib/defaults.js under the axios library file under the node_modules folder.
Custom instance default
Const instance = axios.create ({baseURL: 'https://api.example.com'});
Requested config parameter
Axios ({method:'get', url:' http://bit.ly/2mTM3nY', responseType:'stream'}) .then (function (response) {response.data.pipe (fs.createWriteStream ('ada_lovelace.jpg'))}); axios instance configuration
1. Define some general configurations
Set up BaseUrl
BaseUrl is generally divided into production, development, testing and other addresses. We can get a config.js for storage. If it is vue or react, we can create new env and other files for storage. The following baseUrl uses the environment variables of react.
Set the timeout for timeout requests
Format the data request Content-Type (application/x-www-form-urlencoded, multipart/form-data, application/json...) Wait
Import axios from 'axios'export const request = createAxiosInstance () function createAxiosInstance () {const instance = axios.create ({baseURL: process.env.REACT_APP_BASE_URL, timeout: 5000, headers: {/ / you can define a unified request header post: {' Content-Type': 'application/json'}.}) return instance} 2, add some operations before the request
For example, you need to add token to the request header.
Request parameter null processing
(the example in the figure below passes empty name and personId, which can cause ambiguity. Whether to get empty parameter values or ignore these parameters, some backends will do some processing, but the front end will try to avoid)
Enable loading animation effects every time the interface is requested, etc.
/ / add the request interceptor (what to do before sending the request) instance.interceptors.request.use ((config) = > {/ / add the function loading.open () / / token that enables the loading effect and add the function cleanObject () return config}) in the request header to token & & (config.headers.Authorization = token) / / filter the null undefined'in the request parameters. After the request is returned Add intercept operation
Processing the returned data successfully
For example, the data data returned from the backend may be nested in many layers, and you can directly return the data data you need, so that the business code can get the final data directly without having to deconstruct it every time.
Exception error report after unified processing failure
Interface requests have both successes and failures. If you don't want to write failed logic code every time you write an interface request, and you almost always repeat it, you can focus on unified exception handling for the interface here. For example, judge the status code or the code customized by the backend, and display the error prompt returned by the backend.
/ / add a response interceptor (do something to the response data) instance.interceptors.response.use ((response) = > {/ / you can add the function loading.close () / deconstructing the data that returns the result const res = response.data / / a pair of custom code to judge Return successful data const validateStatus = / ^ (2 | 3)\ d {2} $/ code starts with 2 or 3 as a request for successful if (validateStatus.test (res.code)) {return res / / directly return out we need data} / / judge the failed code code and give a prompt and other operations such as if (res.code = = 401) { Message.error (res.msg)} else {message.warning (res.msg)} return Promise.reject (res)} (error) = > {loading.close () if (error.response.status = 401) {message.error ('token invalid) Please log in again!') RemoveStorageToken () setTimeout (() = > {_ window.location.href ='/ login'}, 2000)} else {if (! window.navigator.onLine) {message.warning ('network exception Please check whether the network is connected properly')} else if (error.code = = 'ECONNABORTED') {message.warning (' request timeout')} else {message.warning ('server exception, please contact the administrator')}} return Promise.reject (error) / / return the error to the specific page})
There are some error handling based on HTTP status code and custom code. After the error is intercepted here, the page does not have to handle the error prompt every time when the business API is called. Of course, it should be configured according to different project requirements.
Unified management of request interface method
In general, we will write all the interface request methods together for unified management, and it is also convenient to find and maintain them when they are changed later.
We can create a new folder to manage api requests (such as apiList) and put our various request files (here by function). For example, user.js stores user-related requests, and so on. The page can then directly reference the method to make the interface call.
Import {request} from'.. / axios'// get user information export function getUserInfo (userId) {return request.get (`/ sys/user/info/$ {userId}`)}
Just call the method directly in the component or page.
Finally, let's put a complete example! You can refer to ~
This sample configuration is suitable for vue or react. Of course, the configuration of each project will be different. Partners should modify the configuration and expand it according to their own projects.
Import axios from 'axios'export const request = createAxiosInstance () function createAxiosInstance () {const instance = axios.create ({baseURL: process.env.REACT_APP_BASE_URL, timeout: 5000 Headers: {/ / you can define a unified request header post: {'Content-Type':' application/json'}...}) / / add a request interceptor (what to do before sending the request) instance.interceptors.request.use ((config) = > {/ / you can add the function loading that enables the loading effect .open () / / token is added to the request header token & & (config.headers.Authorization = token) / / the function cleanObject () return config} of filtering null undefined''in the request parameters) / / add the response interceptor (do something to the response data) instance.interceptors.response.use ((response) = > {/ / you can add the effect of closing loading The function loading.close () / / deconstructs the data that returns the result const res = response.data / / a pair of custom codes to judge Return successful data const validateStatus = / ^ (2 | 3)\ d {2} $/ code starting with 2 or 3 is regarded as a successful request if (validateStatus.test (res.code)) {return res} / / determine the failed code code and prompt for operations such as if (res.code = = 401) {message.error (res.msg)} Else {message.warning (res.msg)} return Promise.reject (res)} (error) = > {loading.close () / / you can add the function if (error.response.status = 401) that turns off the loading effect {message.error ('token invalidation) Please log in again!') RemoveStorageToken () setTimeout (() = > {_ window.location.href ='/ login'}, 2000)} else {if (! window.navigator.onLine) {message.warning ('network exception Please check whether the network is connected properly')} else if (error.code = = 'ECONNABORTED') {message.warning (' request timeout')} else {message.warning ('server exception Please contact the administrator')} return Promise.reject (error) / / return the error to the specific page}) return instance} after reading the above, have you mastered the method of encapsulating the operation method of axios in the vue project? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
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.