In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
In this article, the editor introduces in detail how to use axios in vue, with detailed content, clear steps and proper handling of details. I hope this article "based on how to use axios in vue" can help you solve your doubts.
What is Axios
Axios is a promise-based HTTP library (similar to jQuery's Ajax for HTTP requests)
Can be used in browsers and node.js (both on the client side and on the server side written by node.js)
What are the characteristics of Axios
Support for promise API
Intercept requests and responses
Convert request data and response data
Cancel the request
Automatic conversion of JSON data
Client supports defense against XSRF
III. Axios browser support
4. Install 1. Use npm$ npm install axios2. Use bower$ bower install axios3. Use cdn V, usage (vue project has been built) 1. Basic Axios usage (get, post, put, etc. Request methods)
First, what are the commonly used request methods for Axios: get, post, put, patch, delete
Get: (commonly used) to get data
Post: submit data (form submission + file upload)
Put: update (or edit) data (all data is pushed to the backend (or server))
Patch: update data (only the modified data is pushed to the backend)
Delete: deleting data
Beside the point, in general, in the course of actual development projects:
(1) post: generally used for new projects
(2) put: generally used for updates (suitable for updates with less data)
(3) patch: generally, it is used for a large amount of data. If a form has a large amount of data and there are many items, using put, pushing all the data at once is more performance-consuming. At this time, you can consider using patch to push only the modified data to the backend.
The above extraneous remarks are just general usage and do not mean that they have to be used in this way. Of course, you might say that I use post to get data, okay? Of course this will do, absolutely no problem! How to use it or discuss the decision together with the front and rear to avoid unpleasant physical conflict!
Ha, it's serious, it's a joke!
(1) get request
Mmmm import axios from 'axios' / / get request export default {name: "get", created () {/ / first is called get alias request method / / http://localhost:8080/static/data.json?id=1 axios.get ('.. /.. / static/data.json', {params: {/ / when there are parameters If there is no parameter, just omit id: 1}) .then ((res) = > {console.log ('data:', res)) }) / / the second way to write axios ({method: 'get', url:'.. / static/data.json', params: {id: 1}) .then ((res) = > {console.log ('data:', res)})}}
Let's take a look at the request information-
Status Code:304 Not Modified---304 is redirected; normally, 200 is returned the first time you visit the interface; when you visit the interface for the second time, if the data does not change, the browser will automatically recognize and return a status of 304, which means that the data has not changed or redirected; it is equivalent to redirecting to the resource you just visited, so it will load faster!
(2) post request
Mmmm import axios from 'axios' / / post request export default {name: "post", created () {/ * post commonly used request data (data) format: (1) applicition/json (2) form-data form submission (picture upload) File upload) * / the first way to write is called post alias request method / / http://localhost:8080/static/data.json?id=1 / / applicition/json request let data = {id: 1} axios.post ('.. /.. / static/data.json', data). Then (res) = > {console.log ('data:', res) }) / / the second way to write axios ({method: 'post', url:'.. / static/data.json', data: data,}). Then ((res) = > {console.log ('data:', res)}) / / form-data request let formData = new FormData () for (let key in data) {formData.append (key) Data [key])} axios.post ('.. /.. / static/data.json', formData). Then (res) = > {console.log ('data:', res) })}}
Learn about the differences in Content-Type and parameters between the two post request methods
Applicition/json: as shown below
Form-data: as shown below
(3) put and patch requests
To be clear, put and patch requests are similar to post requests, and there are also applicition/json and form-data. In order to save time, I won't repeat it too much, just write it down!
Mmmm import axios from 'axios' / / put, patch request export default {name: "put,patch", created () {let data = {id: 1} / / put request axios.put ('.. /.. / static/data.json', data). Then (res) = > {console.log ('data:', res) }) / / patch request axios.patch ('.. /.. / static/data.json', data). Then (res) = > {console.log ('data:', res);})}}
(4) delete request
Delete requests are slightly different from the first four requests: delete requests sometimes need to concatenate parameters to URL, and sometimes put parameters in the request body like post requests. As for how to call it, you need to discuss it with the back end!
Mmmm import axios from 'axios' / / delete request export default {name: "delete", created () {/ / delete request axios.delete ('.. /.. / static/data.json', {params: {/ / concatenate parameters to URL id: 1}}) .then (res) = > {console.log ('data:', res) }) axios.delete ('.. /.. / static/data.json', {data: {/ / change params to data and put the parameters in the request body id: 1}). Then ((res) = > {console.log ('data:', res)) }) / / No alias method axios ({method: 'delete', url:'.. / static/data.json', / / params: {id: 1}, / / concatenate the parameters to the URL data: {id: 1} / / put the parameters in the request body}). Then ((res) = > {console.log ('data:' Res)})}}
See the difference between concatenating parameters on URL and putting them in the request body
Params (stitching parameters to URL), as shown below:
Data (put the parameters in the request body), as shown below:
(5) concurrent requests
Concurrent requests: multiple requests are made at the same time, and the return values are processed uniformly.
Mmmm import axios from 'axios' / / concurrent request export default {name: "get", created () {/ / concurrent request uses two methods of axios: axios.all (' parameter is an array') and axios.spread ('callback function') axios.all ([axios.get ('.. /.. / static/data.json')) Axios.get ('.. / static/city.json')] .then (axios.spread ((dataRes, cityRes) = > {console.log (dataRes, cityRes)})} 2. Axios advanced usage (instance, configuration, interceptor, cancel request, etc.)
(1) axios instance and configuration
There are multiple mmmm import axios from 'axios'// axios instance / / backend interface addresses And the timeout length is different export default {name: "get", created () {/ / create axios instance let instance = axios.create ({/ / Parameter configure baseURL: 'domain name (or basic address) of http://localhost:8080',// request) timeout: 3000 timeout / requested timeout (default: 1000 milliseconds (ms) Url:'.. /.. / static/data.json',// request path / / method: 'get',// request method headers: {/ / set the request header (add some parameters to the request header) token:''}, / / params: {id: 1} / / request parameters are spliced on URL / / data: {id: 1} / / request parameters are placed in the request body}) instance.get ('.. /.. / static/data.json', {params: {id: 1}) .then ((res) = > {console.log (res)}) / / if there are two domain names or the timeout length is not the same You can create another axios instance let instance2 = axios.create ({baseURL: 'http://localhost:9090', timeout: 5000}) instance2.get ('.. / static/data.json' {params: {id: 1}) .then ((res) = > {console.log (res)}) / / 1.axios global configuration axios.defaults.baseURL = 'http://localhost:8080'; Axios.defaults.timeout = 3000; / / 2.axios instance configuration let instance = axios.create (); instance.defaults.timeout = 4000; / / 3.axios request configuration instance.get ('.. /.. / static/data.json', {timeout: 6000}). Then (res) = > {console.log (res)}) / / priority from low to high: 1.axios global configuration
< 2.axios实例配置 < 3.axios请求配置 }} (2)拦截器 mmmm import axios from 'axios'// 拦截器:在请求或响应被处理前拦截它们// 请求拦截器、响应拦截器export default { name: "get", created() { //请求拦截器 axios.interceptors.request.use(config =>{/ / what to do before sending the request return config;}, err = > {/ / what to do when the request is wrong return Promise.reject (err);}) / / response interceptor axios.interceptors.response.use (res = > {/ / request successfully processes the response data return res }, err = > {/ / do something in response to the error return Promise.reject (err);}) / cancel the interceptor (understand) let interceptors = axios.interceptors.request.use (config = > {config.headers = {auth: true} return config;}) axios.interceptors.request.eject (interceptors) / / example: the API for login status (token:'') let instance = axios.create ({}); instance.interceptors.request.use (config = > {config.headers.token ='') / / config.headers = {/ / this way of writing will overwrite other parameters in headers, resulting in only one parameter token in headers, so it is not recommended to write / / token:'/ /} return config;}, err = > {return Promise.reject (err);}) / / Mobile pop-up window let instance_phone = axios.create ({}) Instance_phone.interceptors.request.use (config = > {$('# modal'). Show (); return config;}) instance_phone.interceptors.response.use (res = > {$('# modal'). Hide (); return res;})}} 3.Axios further package, practical application in the project
In the vue project, we usually use the axios library, which is a promise-based http library, which can be run on the browser side and node.js. Axios has many excellent features, such as intercepting requests and responses, canceling requests, transforming json, defending clients against XSRF, and so on.
In a complete project, interaction with the server will be frequent, a project will have a lot of requests, and a lot of redundant code. Therefore, it is necessary to encapsulate the request and manage it uniformly.
The main purpose of the axios encapsulation introduced in this article is to help us simplify the project code and facilitate later update and maintenance.
(1) step 1: src/api/request.js
Import axios from 'axios'// import Vue from' vue';// import store from'. / store';// import {router} from'. / router/index'; / / let vm = new Vue (); const instance = axios.create ({baseURL: 'http://localhost:8080', timeout: 3000, / / headers: {/ / post: {/ /' Content-Type': 'application/x-www-form-urlencoded Charset=UTF-8' / /} /}) / / request interception instance.interceptors.request.use (config = > {/ / Custom header, add the project token / / if (store.state.app.token) {/ / config.headers.token = store.state.app.token; / / config.headers.timestamp = new Date (). GetTime (); / /} return config;}, error = > {return Promise.reject (error) }) / / response interception instance.interceptors.response.use (response = > {/ / const resCode = response.status; / / if (resCode = 200) {/ / return Promise.resolve (response); / /} else {/ / return Promise.reject (response); / /} return response;}, error = > {/ / const resCode = error.response.status / / switch (resCode) {/ / case 401: / / vm.$Message.error (error.response.data.message); / / store.commit ('logout', this); / / store.commit (' clearOpenedSubmenu'); / console.log ('token-0', store.state.app.token); / / router.replace ({/ / name:' login' / /}); / / break / / case 404: / / vm.$Message.error ('network request does not exist'); / / break; / / case 500: / / vm.$Message.error ('server connection error'); / / break; / other status code error prompt / / default: / / vm.$Message.error (error.response.data.message); / /} return Promise.reject (error) }) / * * encapsulate the get method * @ param {String} url [request address] * @ param {Object} params request parameters * / export function Get (url, params) {return new Promise ((resolve, reject) = > {instance.get (url, {params: params}). Then ((res) = > {resolve (res.data);}). Catch (error) = > {reject (error.data) })} / * encapsulates post method * @ param {String} url request address * @ param {Object} params request parameters * / export function Post (url, params) {return new Promise ((resolve, reject) = > {instance.post (url, params). Then ((res) = > {resolve (res.data);}). Catch ((error) = > {reject (error.data)) })} / * encapsulates put method * @ param {String} url request address * @ param {Object} params request parameters * / export function Put (url, params) {return new Promise ((resolve, reject) = > {instance.put (url, params). Then ((res) = > {resolve (res.data);}). Catch ((error) = > {reject (error.data)) })} / * encapsulates patch method * @ param {String} url request address * @ param {Object} params request parameters * / export function Patch (url, params) {return new Promise ((resolve, reject) = > {instance.put (url, params). Then ((res) = > {resolve (res.data);}). Catch ((error) = > {reject (error.data)) })} / * encapsulates the delete method * @ param {String} url [request address] * @ param {Object} params [request parameters] * / export function Delete (url, params) {return new Promise ((resolve, reject) = > {instance.delete (url, {params: params}). Then ((res) = > {resolve (res.data);}). Catch ((error) = > {reject (error.data)) })})}
(2) step 2: src/api/index.js
Import {Get,Post,Put,Patch,Delete} from "@ / api/request"; export default {getListData: (params) = > {return Get ('.. /.. / static/data.json',params);}, postListData: (params) = > {return Post ('.. /.. / static/data.json',params);}, deleteListData: (params) = > {return Delete ('.. /.. / static/data.json',params);}}
(3) step 3: src/main.js
/ / The Vue build version to load with the `import`command// (runtime-only or standalone) has been set in webpack.base.conf with an alias.import Vue from 'vue'import App from'. / App'import router from'. / router'import store from'. / store/store'import Api from'. / api/index'; Vue.config.productionTip = falseVue.prototype.$axios = Api / * eslint-disable no-new * / new Vue ({el:'# app', router, store, components: {App}, template:''})
(4) step 4: src/components/HelloWorld.vue
Export default {name: 'HelloWorld', data () {return {}}, methods: {getData () {let data = {id: 1} this.$axios.getListData (data) .then (res) = > {console.log (res) })}, postData () {let data = {id: 1, msg: 2} this.$axios.postListData (data) .then (res) = > {console.log (res);})}, postFormData () {let data = {id: 1, msg: 2} let formData = new FormData () For (let key in data) {formData.append (key, data [key]);} this.$axios.postListData (formData) .then (res) = > {console.log (res) })}, deleteData () {let data = {id: 1} this.$axios.deleteListData (data) .then ((res) = > {console.log (res);})},}, created () {this.getData (); this.postData (); this.postFormData (); this.deleteData () }} here, this article "based on how to use axios in vue" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it. If you want to know more about related articles, please follow the industry information channel.
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.