Vue uses Axios to make AJAX requests

Source: Internet
Author: User

After vue2.0, the Vue-resource is not updated, but it is recommended to use Axios

1. Installing Axios

$ NPM Install Axios

Or

$ Bower Install Axios

2. Introduction of Axios in the file to be used

 from ' Axios '

3. Make a request using Axios

You can axios create a request by passing a related configuration to the只有 url 是必需的。如果没有指定 method,请求将默认使用 get 方法。

{  //' URL ' is the server URL for the requestUrl:'/user',  //' method ' is used when creating a requestMethod'Get',//The default is get//' BaseURL ' will be automatically added to the ' URL ', unless ' URL ' is an absolute URL. //It is possible to pass a relative URL for a method of Axios instances by setting a ' BaseURL 'BaseURL:'https://some-domain.com/api/',  //' Transformrequest ' allows the request data to be modified before sending to the server//can only be used in ' PUT ', ' POST ' and ' PATCH ' several request methods//the function in the following array must return a string, or ArrayBuffer, or Streamtransformrequest: [function (data) {//arbitrary conversion processing of data    returndata; }],  //' Transformresponse ' allows the response data to be modified before being passed to Then/catchtransformresponse: [function (data) {//arbitrary conversion processing of data    returndata; }],  //' Headers ' is the custom request header that is about to be sentHeaders: {'X-requested-with':'XMLHttpRequest'},  //' params ' is the URL parameter that will be sent with the request//must be an unformatted object (plain objects) or Urlsearchparams object  params: {ID:12345  },  //' Paramsserializer ' is a function that is responsible for the ' params ' serialization//(e.g.Https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)Paramsserializer:function (params) {    returnQs.stringify (params, {arrayformat:'brackets'})  },  //' data ' is what is sent as the principal of the request//apply only to these 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-specific: FormData, File, Blob//-Node Exclusive: Streamdata: {firstName:'Fred'  },  //' Timeout ' specifies the number of milliseconds the request timed out (0 means no time-out)//if the request is over the time of ' timeout ', the request will be interruptedTimeout +,  //' withcredentials ' indicates whether credentials need to be used when cross-domain requestsWithcredentials:false,//the default//' Adapter ' allows custom processing of requests to make testing easier//returns a promise and applies a valid response (consult [Response docs] (#response-api)).adapter:function (config) {/* ... */  },  //' auth ' indicates that HTTP Basic authentication should be used and provide credentials//this will set a ' Authorization ' header, overwrite any existing custom ' Authorization ' header that uses ' headers ' settingsAuth: {username:'JaneDoe', Password:'S00pers3cret'  },  //' Responsetype ' indicates the data type of the server response, can be ' arraybuffer ', ' blob ', ' document ', ' json ', ' text ', ' stream 'Responsetype:'JSON',//the default//' Xsrfcookiename ' is the name of the cookie used as the value of XSRF tokenXsrfcookiename:'Xsrf-token',//default//' Xsrfheadername ' is the name of the HTTP header that hosts the value of XSRF tokenXsrfheadername:'X-xsrf-token',//the default//' onuploadprogress ' allows progress events to be processed for uploadonuploadprogress:function (progressevent) {//handling of native progress events  },  //' ondownloadprogress ' allows progress events to be processed for downloadondownloadprogress:function (progressevent) {//handling of native progress events  },  //' maxcontentlength ' defines the maximum size of the allowed response contentMaxcontentlength: -,  //the ' validatestatus ' definition for a given HTTP response status code is resolve or reject promise. If ' validatestatus ' returns ' true ' (or set to ' null ' or ' undefined '), promise will be resolve; Otherwise, promise will be rejectevalidatestatus:function (status) {returnStatus >= $&& Status < -;//the default  },  //' maxredirects ' defines the maximum number of redirects follow in node. js//if set to 0, no redirection will be followMaxRedirects:5,//the default//' httpagent ' and ' httpsagent ' are used in node. js to define custom proxies to use when executing HTTP and HTTPS. Allow configuration options like this://' keepAlive ' is not enabled by defaultHttpagent:Newhttp. Agent ({keepAlive:true}), Httpsagent:NewHttps. Agent ({keepAlive:true }),  //' proxy ' defines the host name and port of the proxy server//' auth ' means that HTTP Basic authentication should be used to connect to the proxy and provide credentials//this will set a ' proxy-authorization ' header and overwrite the existing custom ' Proxy-authorization ' header set by using ' header '. Proxy: {host:'127.0.0.1', Port:9000, Auth:: {username:'Mikeymike', Password:'rapunz3l'    }  },  //' Canceltoken ' specifies the cancel token to use for canceling the requestCanceltoken:NewCanceltoken (function (cancel) {})}

For convenience, all supported request methods provide aliases:

Axios.request (config) axios.get (url[, config]) axios.delete (url[, config) axios.head (url[, config]) axios.post (url[, data[, Config]]) axios.put (url[, data[, config]) axios.patch (url[, data[, Config])

4. Response structure of the request

 { //  "data ' Server-supplied response   data: {},  //  status: 200   //  ' statustext ' HTTP from server response Status information  statustext:  " ok  "   //  ' headers ' server response header   headers: {},  //  ' config ' is the configuration information provided for the request   config: {}}  

thenwhen used, you will receive a response such as the following:

Axios. Get ('/user/12345')  . Then (function (response) {    console.log (response.data);    Console.log (response.status);    Console.log (response.statustext);    Console.log (response.headers);    Console.log (Response.config);  });

When used catch , the response can be error used by the object

Axios.post ('/user', {    'Fred',     ' Flintstone '   })  . Catch (function (Error) {    console.log (error);  });

5. Usage examples

El1:get Request

Axios. Get ('/user', {    params: {      12345    }  })  . Then (function (response) {    Console.log (response);  })  . Catch (function (Error) {    console.log (error);  });

El2:post Request

Axios.post ('/user', {    'Fred',     ' Flintstone '   })  . Then (function (response) {    Console.log (response);  })  . Catch (function (Error) {    console.log (error);  });

EL3: Executing multiple concurrent requests

function Getuseraccount () {  return Axios.  Get('/user/12345');} function Getuserpermissions () {  return Axios.  Get('/user/12345/permissions');} Axios.all ([Getuseraccount (), Getuserpermissions ()])  . Then (Axios.spread (function (acct, perms) {     // Two requests are now complete  }));

Vue uses Axios to make AJAX requests

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.