1. Basic Concepts
1.1 Ajax
Ajax stands for “Asynchronous JavaScript and XML”. At its core it is made up of the JavaScript, XmlHttpRequest, and DOM objects: through the XmlHttpRequest object it sends an asynchronous request to the server, gets data back from the server, and then uses JavaScript to manipulate the DOM and update the page.
Taking Jquery as an example:
| |
Common parameter descriptions:
Property parameters:
- type: the request method — post, get, put, delete, etc.; defaults to get.
- url: the address to send the request to, a String parameter; defaults to the current page’s address.
- timeout: sets the request timeout, a Number parameter, in milliseconds.
- async: whether the request is asynchronous, a Boolean parameter; defaults to true.
- cache: whether to cache, a Boolean parameter; defaults to true — when dataType is script or jsonp, the default is false.
- data: the request parameters, an Object or String parameter.
- dataType: the expected data type the server returns, a String parameter; one of xml, html, script, json, jsonp, text.
- contentType: the encoding type; defaults to “application/x-www-form-urlencoded”.
Callback parameters:
- beforeSend: the function called before the request is sent.
- complete: the function called after the request completes.
- success: the function called after the request succeeds.
- error: the function called when the request fails.
Finally, Jquery provides a global setup function, $.ajaxSetup, for handling certain operations uniformly.
1.2 XMLHttpRequest
XMLHttpRequest is used to exchange data with the server in the background. After the page loads, it sends data to the server in the background, so the page can be updated without reloading it.
Let’s look at an example first:
| |
Methods:
- open: initialize the request.
- send: send the request.
- abort: ignore the XmlHttp object and return to the uninitialized state, which also means terminating the request.
- setRequestHead: set the request headers, for example the request encoding format.
- getResponseHead: get a specified response header.
- getAllResponseHead: get all response headers.
Properties:
- readyState: the working state — 0 (uninitialized), 1 (initialized), 2 (sending data), 3 (data in transit), 4 (completed); 5 values in total.
- status: holds the response status code.
- statusText: holds a short description of the response status code.
- responseText: holds the response text, stored as text.
- responseXML: holds the response as an XML document model object; if the response is text, this value is null.
Callbacks:
- onreadystatechange: the function called when the state changes.
2. Axios
Axios is a Promise-based HTTP client for the browser and Nodejs, with the following features:
- Supports the Promise API
- Intercepts requests and responses
- Transforms request and response data
- Cancels requests
- Automatically converts JSON data
- The client supports protection against CSRF/XSRF
2.1 Using Method Aliases
Let’s look at an example first:
| |
Available 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]])
2.2 Configuring with the Config Method
Let’s look at an example
| |
2.3 Parameter Configuration
- url: the url used to send a request to the server.
- method: the request method; defaults to the get method.
- baseURL: the base URL path. If url is not an absolute path, e.g. http://domain.com/api/login?name=jack, then the URL sent to the server will be baseURL + url.
- transformRequest: the transformRequest method allows the request to be modified before it is sent to the server; this method only applies to the PUT, POST, and PATCH methods. It must return a string, ArrayBuffer, or Stream in the end.
- transformResponse: the transformResponse method allows the response data to be modified before the data is passed to then or catch. This method must also return data in the end.
- headers: send custom Headers; the headers contain various pieces of information about the HTTP request.
- params: params is the query parameter object for the request; the data in the object is concatenated into url?param1=value1¶m2=value2.
- paramsSerializer: the params serializer.
- data: data is the data object sent with a POST, PUT, or PATCH request.
- timeout: the request timeout setting, in milliseconds.
- withCredentials: indicates whether a cross-domain request needs to use credentials.
- adapter: adapter lets the user handle requests in a way that is easier to test. It returns a Promise and a valid response.
- auth: auth indicates that credentials are provided for HTTP authentication. This sets an Authorization header. A custom Authorization must be set in headers.
- responseType: the data type in which the server will return the response — one of arraybuffer, blob, document, json, text, stream; the default is json-like data.
- xsrfCookieName: the name of the cookie used as the xsrf token value.
- xsrfHeaderName: the name of the HTTP header carrying the xsrf token value.
- onUploadProgress: allows some operations to be performed during upload.
- onDownloadProgress: allows some operations to be performed during download.
- maxContentLength: defines the maximum length of the received response data.
- validateStatus: validateStatus defines whether to resolve or reject the returned promise based on the HTTP response status code. If validateStatus returns true (or is set to null or undefined), the promise will be resolved; otherwise, the promise will be rejected.
- maxRedirects: maxRedirects defines the maximum number of redirects in Node.js; if set to 0, there are no redirects.
- httpAgent: defines the agent used for http requests.
- httpsAgent: defines the agent used for https requests.
- proxy: proxy defines the hostname and port of the proxy server.
- cancelToken: cancelToken defines a cancel token used to cancel requests.
2.4 Concurrency Methods
Axios supports concurrent data transmission.
- axios.all(iterable)
- axios.spread(callback)
| |
2.5 Creating an Instance
You can create an instance with custom settings, apply a specific configuration, and keep using that instance to request data.
| |
2.6 Global Configuration
axios supports global default settings
| |
2.7 Axios vs. Jquery
- Axios supports Node.js; Jquery does not
- Axios is a Promise-based network request library that is smaller and more purpose-built than Jquery.
