Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to encapsulate axios request in vue

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces the knowledge of "how to encapsulate axios requests in vue". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Axios

Axios is a promise-based HTTP library, which can be used in browsers and node.js, and it is also a http library officially recommended by vue. Encapsulating axios, on the one hand, for future maintenance convenience, on the other hand, you can also customize the processing of requests.

Installation

Npm i axios

Encapsulation

I encapsulated the axios request in http.js and re-encapsulated the get request, the post request.

First, introduce axios

Import axios from 'axios'

Set the interface request prefix

Generally speaking, our developers will have development, testing and production environments. Prefixes need to be distinguished. We use node environment variables to make judgments.

If (process.env.NODE_ENV = = 'development') {axios.defaults.baseURL =' http://dev.xxx.com'} else if (process.env.NODE_ENV = = 'production') {axios.defaults.baseURL =' http://prod.xxx.com'}

When debugging in localhost, using the development address directly will generally have cross-domain problems, so we also need to configure the proxy

This project is built by vue cli3, and the agent configuration is in the vue.config.js file:

Module.exports = {devServer: {proxy: {'/ proxyApi': {target: 'http://dev.xxx.com', changeOrigin: true, pathRewrite: {' / proxyApi':'}}}

This successfully points / proxyApi to 'http://dev.xxx.com', which restarts the service.

Modify the configuration in http.js

If (process.env.NODE_ENV = = 'development') {axios.defaults.baseURL =' / proxyApi'} else if (process.env.NODE_ENV = = 'production') {axios.defaults.baseURL =' http://prod.xxx.com'}

Interceptor

Then set the timeout and request header information

Axios.defaults.timeout = 10000 Content-Type' / request header information is set for the post request axios.defaults.headers.post ['Content-Type'] =' application/x-www-form-urlencoded;charset=UTF-8'

Axios is easy to use, one of which is that its interceptor is very powerful, so we can set interceptors for requests and responses. For example, the request interceptor can add token to each request, and it is convenient to maintain it after unified processing. The response interceptor can do a layer of operation after receiving the response, such as judging login status and authorization according to the status code.

/ / request interceptor axios.interceptors.request.use (config = > {/ / determine whether a token exists before each request is sent / / if so, add token to the header of the http request, so that the backend judges your login according to the token Here token is usually the token & & (config.headers.Authorization = token) return config} stored in the localstorage by the user after login, error = > {return Promise.error (error)}) / / response interceptor axios.interceptors.response.use (response = > {/ / if the returned status code is 200, indicating that the API request is successful You can get the data normally / / otherwise throw the error if (response.status = 200) {if (response.data.code = 511) {/ / unauthorized access authorization interface} else if (response.data.code = 510) {/ / unlogged in jump login page} else {return Promise.resolve (response)}} else {return Promise.reject (response)}} Error = > {/ / We can handle the exception status uniformly here if (error.response.status) {/ / failure of processing request / / A pair of different return codes deal with return Promise.reject (error.response)}})

Encapsulation of get post

HttpGet: one parameter is the url of the request, the other is the request parameter carried, and the promise object is returned.

/ / get request export function httpGet ({url, params = {}}) {return new Promise ((resolve, reject) = > {axios.get (url, {params}). Then ((res) = > {resolve (res.data)}) .catch (err = > {reject (err)}

HttpPost: the principle is similar to that of get. It should be noted that there is an extra data parameter, which needs to be operated on the sequence number before the post request is submitted, which is processed through transformRequest. The other two parameters url,params and get request are the same.

/ post request export function httpPost ({url, data = {}, params = {}}) {return new Promise ((resolve, reject) = > {axios ({url, method: 'post', transformRequest: [function (data) {let ret =' for (let it in data) {ret + = encodeURIComponent (it) +'='+ encodeURIComponent (data [it]) +'&'} return ret}], / / data sent data / / url parameter params}) .then (res = > {resolve (res.data)}

How to use

I put all the interface calls in the api.js file

First introduce the encapsulated method, and then re-encapsulate the interface to be called into a method to expose it.

Import {httpGet, httpPost} from'. / http'export const getorglist = (params = {}) = > httpGet ({url: 'apps/api/org/list', params})

You can call this in the page:

/ / .vueimport {getorglist} from'@ / assets/js/api'getorglist ({id: 200}) .then (res = > {console.log (res)})

In this way, the api can be managed in a unified way, and future maintenance changes only need to be operated in the api.js file.

Complete code

Finally, paste the complete code.

/ / switching if for http.jsimport axios from 'axios'// environment (process.env.NODE_ENV =' development') {axios.defaults.baseURL ='/ proxyApi'} else if (process.env.NODE_ENV = 'production') {axios.defaults.baseURL =' http://prod.xxx.com'}// request interceptor axios.interceptors.request.use (config = > {token & & (config.headers.Authorization = token) return config}) Error = > {return Promise.error (error)}) axios.defaults.timeout = 10000axios.defaults.headers.post ['Content-Type'] =' application/x-www-form-urlencoded Charset=UTF-8'// response interceptor axios.interceptors.response.use (response = > {if (response.status = 200) {if (response.data.code = 511) {/ / unauthorized access authorization interface} else if (response.data.code = 510) {/ / unlogged in jump login page} else {return Promise.resolve (response)}} else {return Promise.reject (response)}} Error = > {/ / We can uniformly handle the abnormal state here if (error.response.status) {/ / failure of processing request / / A pair of different return codes to process return Promise.reject (error.response)}}) / / get request export function httpGet ({url, params = {}}) {return new Promise ((resolve, reject) = > {axios.get (url)) {params}) .then ((res) = > {resolve (res.data)}) .catch (err = > {reject (err)})} / / post request export function httpPost ({url, data = {}, params = {}}) {return new Promise ((resolve, reject) = > {axios ({url, method: 'post') TransformRequest: [function (data) {let ret =''for (let it in data) {ret + = encodeURIComponent (it) +' ='+ encodeURIComponent (data [it]) +'&'} return ret}], / / data sent data, / / url parameter params}) .then (res = > {resolve (res.data)})} / / api.jsimport {httpGet HttpPost} from'. / http'export const getorglist = (params = {}) = > httpGet ({url: 'apps/api/org/list', params}) export const save = (data) = > {return httpPost ({url:' apps/wechat/api/save_member', data})} / / .vueimport {getorglist} from'@ / assets/js/api'export default {name: 'upload-card', data () {} Mounted () {getorglist ({id: 200}). Then (res = > {/ / console.log (res)})},} "how to encapsulate axios requests in vue" ends here Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report