Vue uses Axios for ajax request details, and vueaxiosajax for details
After vue2.0, we recommend that you use axios instead of updating vue-resource.
1. Install axios
$ npm install axios
Or
$ bower install axios
2. Introduce axios in the file to be used
import axios from 'axios'
3. Use axios for requests
You can create a request by passing related configurations to axios. Only url is required. If no method is specified, the get method is used by default for requests.
{// 'Url' is the server url used for the request: '/user', // 'method' is the method used to create the request: 'get ', // by default, get // 'baseurl' is automatically added before 'url', unless 'url' is an absolute url. // It can set a 'baseurl' to facilitate the transmission of the relative URL baseURL: 'https: // some-domain.com/api/' for the axios instance, // 'transformrequest' can be sent to the server before, modify request data // it can only be used in 'put', 'post', and 'patch 'request methods. // the function in the following array must return a string, ArrayBuffer, or Stream transformRequest: [function (data) {// return data for any conversion of data;}], // 'transformresponse' allows you to modify the response data transformResponse before being passed to then/catch: [function (data) {// convert data to return d Ata;}], // 'headers' is the custom request header headers: {'x-Requested-with': 'xmlhttprequest '}, // 'params 'is the URL parameter to be sent along with the request // it must be a plain object or URLSearchParams object params: {ID: 12345 }, // 'paramsserializer' is a function responsible for 'params' serialization // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function (params) {return Qs. stringify (params, {arrayFormat: 'brackets' })}, // 'Data' is the data sent as the request body // only applicable to these request methods 'put', 'post ', and 'pa' // when 'transformrequest' is not set, it must be one of the following types: //-string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams //-exclusive to the browser: formData, File, Blob //-Node exclusive: Stream data: {firstName: 'fred '}, // 'timeout' specifies the number of milliseconds for request timeout (0 indicates no timeout time) // if the request call fee exceeds the 'timeout' time, the request will be interrupted: timeout: 1000, // 'withcredentials 'indicates whether to use the credential withCredential for cross-origin requests S: false, // default // 'adapter 'allows custom request processing, to make the test easier // return a promise and apply a valid response (refer to [response docs] (# response-api )). adapter: function (config ){/*... * //}, // 'auth 'indicates that HTTP basic authentication should be used and creden/ are provided. // This sets a 'authorization' header, overwrite the existing custom 'authorization' header auth: {username: 'janedoe ', password: 's00pers3cret'} set by 'headers '}, // 'responsetype 'indicates the Data Type of the server response, which can be 'arraybuffer', 'blob', 'document', 'json', or 'text ', 'Stream' responseType: 'json', // The default // 'xsrfcookiename' is the name of the cookie used as the xsrf token value xsrfCookieName: 'xsrf-token ', // default // 'xsrfheadername' is the name of the HTTP header that carries the xsrf token value xsrfHeaderName: 'x-XSRF-TOKEN ', // default // 'onuploadprogress' allows onUploadProgress: function (progressEvent) to process progress events for uploads {// processing native progress events }, // 'ondownloadprogress' allows you to handle the progress event onDownloadProgress for download: function (progressEvent ){// Processing native progress events}, // 'maxcontentlength' defines the maximum size of the allowed response content maxContentLength: 2000, // 'validatestatus' defines whether the given HTTP response status code is resolve or reject promise. If 'validatestatus' returns 'true' (or is set to 'null' or 'undefined'), promise will be resolve; otherwise, promise will be rejecte validateStatus: function (status) {return status> = 200 & status <300; // default value}, // 'maxredirects' is defined in node. in js, the maximum number of follow redirects // if it is set to 0, no redirection maxRedirects: 5 will be performed. // The default value of // 'httpagent' and 'httpsagent' are in node. js is used to define the custom proxy used when http and https are executed. The following configuration options are allowed: // 'keepalive' is disabled by default: httpAgent: new http. agent ({keepAlive: true}), httpsAgent: new https. agent ({keepAlive: true}), // 'proxy' defines the host name and port of the proxy server // 'auth' indicates that HTTP basic verification should be used to connect to the proxy, and provide creden/ // This will set a 'proxy-authorization' header, overwrite the existing custom 'proxy-authorization' header set by 'header. Proxy: {host: '2017. 0.0.1 ', port: 9000, auth: {username: 'mikeymi', password: 'rapunz3l'}, // 'canceltoken' specifies the cancel token used to cancel the request: new CancelToken (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. Request Response Structure
{// 'Data' response data: {} provided by the server, // 'status' indicates the HTTP status code status: 200 returned by the server, // 'statustext 'HTTP status information returned by the server statusText:' OK ', // 'headers' header of the Server Response headers :{}, // 'config' is the configuration information provided for the request. config :{}}
When using then, you will receive the following response:
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 catch is used, the response can be used through the error object.
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .catch(function (error) { console.log(error); });
5. Use instances
El1: get request
axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
El2: post request
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
El3: execute multiple concurrent requests
Function getUserAccount () {return axios. get ('/user/100');} function getUserPermissions () {return axios. get ('/user/12345/permissions');} axios. all ([getUserAccount (), getUserPermissions ()]). then (axios. spread (function (acct, perms) {// both requests are executed now }));
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.