Use of axios
1. Features of axios
? 1. Axios is based on promise HTTP client for browser and node.js
? 2. Create XMLHttpRequest from browser
? 3. Make http request from node.js
< p>? 4. Intercept (interceptor) request and response
? 5. Convert request and response data
? 6. Cancel request
? 7. Automatically convert JSON data
? 8. The client supports to prevent CSRF/XSRF attacks
? 9. Support promiseAPI
2. Some commonly used initial configuration
axios.defaults.baseURL ='https://www.easy-mock.com/mock/5b0412beda8a195fb0978627/temp';// The default route axio Executing the method in the interceptor) axios.defaults.validateStatus = function validateStatus(status) {//=>Customize the success and failure rule: RESOLVE / REJECT (default rule: the status code starts with 2 as success) return /^(2 |3)\d{2}$/.test(status);}; //=>Set the format of the content sent to the server based on the request body in the POST request, the default is RAW, and the URL-ENCODEED format is commonly used in projects axios.defaults.headers['Content-Type'] ='appliction/x-www-form-urlencoded';axios.defaults.transformRequest = data => {//=>DATA: is the request body that needs to be passed to the server Content (object) let str = ``; for (let attr in data) { if (data.hasOwnProperty(attr)) {str += `${attr}=${data[attr]}&`;}} return str.substring(0, str.length-1);};
3. Some usage methods
1. Use of get/post request
// Writing a method this.axios({ url: "", // route submitted data: {}, // data submitted by post request params: {}, // get data submitted by request methods: "", / / Request method}).then(function(response) {// Callback function executed after successful execution}).catch(function(response) {// Triggered when the then method throws an exception})// Writing method 2: Directly How to get the request type in axios // get request axios.get('url',{ data: {}, // data submitted by post request params: {}, // get data submitted by request, displayed on the url }).then(function(res){ console.log(res);//The successfully processed function is equivalent to success)).catch(function(error){ console.log(error)// Print the exception thrown by the then function })// post request axios.post('url',{ data: {}, // the data submitted by the post request params: {}, // get the data submitted by the request, displayed on the url}).then(function (res){ console.log(res);//The successfully processed function is equivalent to success)).catch(function(error){ console.log(error)//Print the exception thrown by the then function))
Supplement: Other request methods (understanding)
axios.get(url {data , Configuration}) axios.delete(url {data, configuration}) axios.head(url {data, configuration}) axios.post(url {data, configuration}) axios.put(url {data, configuration}) axios. patch(url {data, configuration})// When using the alias method, there is no need to specify the url, method and data attributes in the config
configuration in the request h6>
1. `url` is the server URL that will be used for the request url:'/user', 2. `method` is the request method used when making the request method:'get', // Default 3. `baseURL` will be added in front of `url` unless `url` is absolute. // It is convenient to set `baseURL` for an instance of axios, so that the relative URL can be passed to the method of the instance. baseURL:'https://some-domain.com/api/', 4. `transformRequest` allows the request data to be changed before it is sent to the server // This only applies to the request methods'PUT','POST' and 'PATCH'// The last function in the array must return a string, an ArrayBuffer or a Stream transformRequest: [function (data) {// do any data transformation you want and then return data;}], 5. ` transformResponse` allows to change the response data before then / catch transformResponse: [function (data) {// do any data transformation you want and return data; }], 6. `headers` is the custom headers to be sent : {'X-Requested-With':'XMLHttpRequest'},7. `params` is the URL parameter to be sent with the request // Must be a pure object or URLSearchParams object params: {ID: 12345}, 8. `paramsSerializer `Is an optional function, responsible for serializing `params`// (eg https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)paramsSerializer: function (params) {return Qs.stringify(params, {arrayFormat:'brackets'})}, 9. `data` is the data to be sent as the request body // Only applicable to request methods "PUT", "POST" and " PATCH" // When `transformRequest` is not set, it must be one of the following types: //-string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams //-Browser only: FormData, File, Blob //-Node only: Streamdata : {firstName:'Fred'}, 10. `timeout` specifies the request timeout The number of milliseconds before. // If the requested time exceeds the'timeout', the request will be aborted. timeout: 1000,11. `withCredentials` indicates whether to request cross-site access control withCredentials: false, // default12. `adapter' allows custom processing of requests, which makes testing easier. // Return a promise and provide a valid response (see [response docs](#response-api)) adapter: function (config) {/*… */}, 13. `auth' means that HTTP basic authentication should be used, And provide credentials. // This will set an `Authorization' header, overwriting any existing `Authorization' custom header, using the `headers` setting. auth: {username:'janedoe', password:'s00pers3cret'}, 14. "responseType" indicates the type of data the server will respond to // including'arraybuffer','blob','document','json','text' ,'stream'responseType:'json', // default 15. `xsrfCookieName` is the name of the cookie to be used as the value of the xsrf token xsrfCookieName:'XSRF-TOKEN', // default 16. `xsrfHeaderName` is to carry xsrf The name of the http header of the token value xsrfHeaderName:'X-XSRF-TOKEN', // default 17. `onUploadProgress` allows processing upload progress events onUploadProgress: function (progressEvent) {// Use local progress events to do whatever you want Do}, 18. `onDownloadProgress` allows processing of download progress events onDownloadProgress: function (progressEvent) {}, 19. `maxContentLength` defines the maximum size of http response content allowed maxContentLength: 2000, 20. `validateStatus` defines whether to parse Or reject the given promise // HTTP response status code. If `validateStatus` returns `true` (or set to `null`, promise will be resolved; otherwise, promise will be rejected. validateStatus: function (status) {return status >= 200 && status <300; // default }, 21. `maxRedirects` defines the maximum number of redirects to follow in node.js. // If set to 0, redirects will not be followed. maxRedirects: 5, // default 22. `httpAgent` and ` httpsAgent` is used to define a custom agent used when executing http and https requests in node.js respectively. // Allows to configure options similar to `keepAlive`, // not enabled by default. httpAgent: new http.Agent({ keepAlive: true }),httpsAgent: new https.Agent({ keepAlive: true }), 23.'proxy' defines the hostname and port of the proxy server // `auth` indicates that HTTP Basic auth should be used to connect to the proxy and provide credentials.// This will set a `Proxy-Authorization` header, overwriting any existing `Proxy-Authorization` custom headers set with `headers`. proxy: {host: '127.0.0.1', port: 9000, auth:: {username:'mikeymike', password:'rapunz3l' }}, 24. "cancelToken" specifies the cancellation token that can be used to cancel the request cancelToken: new CancelToken(function (cancel) {})}
< h5 id="axios's concurrency realization">2.axios's concurrency realization
let axiosList = [this.axios({}), this.axios({})] this.axios.all(axiosList).then(axios.spread(function(response1, response2) {// response1, response2 are the return values of the two concurrently executed axios callback functions})).catch(axios.spread(function(response1, response2) {// response1, response2 are two concurrently executed axios, respectively The exception thrown by the callback function then}))// axios is based on promise, and promise is a way to solve asynchronous programming. If you want to achieve axios concurrency, you can first put each axios event in the list, through axios The internal all method implements the concurrent execution of multiple axios events.
Some writings about the configuration method (for reference only):
export default {name: "Test", data() {return {input:'', msg:'',} }, methods: {submitA() {if (this.input) { // // The callback function cannot directly use the data defined in the data in the component. In other words, the value obtained by the callback function cannot be assigned to the value of the data in the component // // The reason is that this in axios refers to Vue, you can use a variable to cache Vue before executing axios, // // For example, define a variable and assign the this referred to by Vue to the variable. In other places, you can use the variable instead of this let that = this; // this.$axios({ // url:'http://127.0.0.1:8000/test/', // methods: "get", // // params: {// // input_a: this.input, // // }, // The data requested by get is placed in request.GET // data: {// input_a: this.input, // }, // The post request backend cannot get error // }).then(function (response) {// // The callback function cannot directly use the data defined in the component data. In other words, the value obtained by the callback function cannot be assigned Give the value of data in the component // // The reason is that this in axios refers to Vue. You can use a variable to cache Vue before executing axios, // // For example, define a variable and refer to this as Vue Assign a value to this variable, you can use this variable in other places instead of this // that.msg = response.data.msg; // }).catch(function (error) {// console.log(error) // print The exception thrown by the then function // }) this.$axios.get( "http://127.0.0.1:8000/test/", {params: {input_a: that.input}, headers:{'Content-Type' :'appliction/x-www-form-urlencod ed'), responseType:'json',} ).then(function (response) {that.msg = response.data.msg }).catch(function (response) {that.msg = response.data.msg }) ;}}} }