Ajax technology
Ajax
Is a commonly used andWeb
Server communication technology currently sentAjax
There are four main ways to request:
- Native XHR
- In the jquery $. Ajax ()
- axios
- fetch
In recent years, the most common use of XHR was jquery ajax requests, but in recent years, the front end has lost its luster and been replaced by the emergence of Axios and FETCH, both of which are starting to occupy the important front end area of “requests.” At present, you only need to be skilled in using Axios. Jquery ajax will gradually be phased out by The Times. Fetch is in line with the trend of the front end, but it is not mature yet and is not as convenient as Axios.
Jquery ajax
$.ajax({
type:"GET".url:url,
data:data,
dataType:dataType
success:function(){},
error:function(){}})Copy the code
Ajax is jquery’s encapsulation of native XHR, but also adds jSONP support to make Ajax requests cross-domain. See this article about ajax requests in five steps.
However, it is important to note that the JSONP request is either an XHR asynchronous request or a JS file, so the jSONP cross-domain request is not visible under the XHR TAB in the network panel of the browser, but it is visible under the JS TAB.
- Faults (reasons for slowly being abandoned) :
- To use jquery Ajax, you must import jquery’s entire large file
- Jquery Ajax itself is a programming for MVC design pattern, which is not in line with the current popular frameworks such as VUE and React based on MVVM pattern
- The essence of jquery Ajax is the encapsulation based on XHR, but the architecture of XHR itself is not very clear. Fetch has been adopted as an alternative solution
conclusion
With the rise of the new generation framework of Vue and React based on MVVM mode in the front end, and the development of new specifications such as ES6, such large and complete JS libraries as Jquery are destined to go down.
Axios
What is Axios?
Axios is a PROMISe-based HTTP library that automatically determines the current environment and freely switches between the browser and node.js environment. Browsers will implement XMLHttpRequests; In the case of a Node environment, this is implemented based on node’s built-in core HTTP module. At the same time, it also handles the response results with promises to avoid getting stuck in callback hell.
Not only that, but Axios can intercept requests and responses, transform request data and response data, interrupt requests, automatically convert JSON data, client-side support for defensive XSRF, and more.
axios({
method: 'post',
url: '/login',
data: {
username:'jackson',
password:'yyqx1128'
}
})
.then(function (res) {
console.log(res);
})
.catch(function (err) {
console.log(err);
});
Copy the code
This ajax request method is recommended by Yu Yuxi, author of the Vue framework. Axios is essentially a wrapper based on native XHR, but it’s an implementation of ES6’s new syntax Promise. And has the following characteristics:
- Create XHR from the browser
- Create an HTTP request from node.js
- Supporting promise API
- Provides an interface for concurrent requests (important, easy to operate)
- Interception of requests and responses
- Support for cancellation requests
- The client can defend against CSRF attacks
Write Axios core principles by hand
1. Basic use
The basic use of AXIos is as follows:
- axios(config)
- axios.method(url,data,config)
// The following are the available instance methods. The specified configuration is merged with the configuration of the instance
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]])
Copy the code
Axios ({method: 'POST ', URL :' /user/12345', data: {username:' Jackson ', password:'yyqx1128'}}); Axios. GET ('/user? ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });Copy the code
2. Implement axios
The use of axios(config) shows that the exported Axios is a method, and the use of axios.get() shows that the exported Axios prototype has methods such as GET, POST,put,delete, etc.
By analysis, axios is actually a method in an Axios class. We can start by writing a request method that implements the main request function, which can be invoked using the axios(config) form.
class Axios{
constructor(){... }request(config){
return new Promise((resove) = > {
const {url=' ', data={}, method='get'} = config; // Structure parameters
const xhr = new XMLHttpRequest; // Create the request object
xhr.open(method, url, true);
xhr.onreadystatechange = () = > {
if(xhr.readyState == 4 && xhr.status == 200) {
resove(xhr.responseText);
// When the asynchronous request returns, convert the Promise to a successful state and export the result} } xhr.send(data); }}})function CreateAxiosFn() {
let axios = new Axios;
let res = axios.request.bind(axios);
return req;
}
let axios = CreateAxiosFn();
Copy the code
Then build a simple server-side code to test the effect of the request:
const express = require('express') let app = express(); app.all('*', function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Content-Type'); res.header('Access-Control-Allow-Methods', '*'); res.header('Content-Type', 'application/json; charset=utf-8'); next(); }); app.get('/getInfo', function(request, response){ let data = { 'username':'jackson', 'age':'20', }; response.json(data); }); App.listen (3000, function(){console.log(" server start "); });Copy the code
After starting the server, test the success of the request in the page:
<button onclick="getMsg()">Click on the</button>
<script src="./axios.js"></script>
<script>
function getMsg(){
axios({
method: 'get'.url: 'http://localhost:3000/getInfo'
}).then(res= > {
console.log(res); })}</script>
Copy the code
After clicking the button, you can see that the request succeeds and the data is retrieved.
conclusion
In addition to encapsulating native XHR like jquery Ajax, Axios provides a variety of interfaces such as concurrent request, interception, and so on. At the same time, Axios is relatively small, and does not have the problems of fetch, which can be said to be the best ajax request method.
3. The interceptor
Intercept requests or responses before they are processed by THEN or catch.
// ----------- Requests to intercept --------
axios.intercepters.request.use(function(config) {
// Before sending the request
console.log(Request interception:,config); // Data processing
return config;
},function(error) {
return Promise.reject(error);
})
// ----------- Response intercept --------
axios.intercepters.response.use(function(response) {
return response;
}, function(error) {
return Promise.reject(error);
})
Copy the code
axios.interceptors.response.use
andaxios.interceptors.request.use
To define interception methods for requests and responses.
An interceptor, as its name implies, intercepts and performs some processing of the actual operation data before the request and the response. So how to do that? First of all, the interceptor is also a class that manages responses and requests.
class InterceptorsManage {
constructor(){
this.handlers = [];
}
use(onFulField, onRejected) {
// Store successful and failed callbacks in the queue
this.handlers.push({
onFulField,
onRejected
})
}
}
Copy the code
This shows that axios has a response interceptor and a request interceptor, so how to implement this in Axios:
class Axios{
constructor(){
this.interceptors = {
request: new InterceptorsManage,
response: new InterceptorsManage
}
}
//....
}
Copy the code
Add the Interceptors property to the Axios constructor, and then define the Request and response properties to handle the request and response.
When the use method is executed, the incoming callback function is placed in the Handlers array.
Fetch
try{
var response=await fetch(url);
var data=response.json();
console.log(data);
}catch(e){
console.log('error is'+e);
}
Copy the code
Ajax and Axios are essentially packages of native XHR, but Fetch is a replacement for the new XHR. Its features are as follows:
- Lower level, with richer APIS
- Not based on XHR, is the implementation of the new ES specification
However, there are still many problems with Fetch:
- The FETCH will only report errors for network requests; 400,500 requests will be considered successful
- Fetch does not contain cookies by default, and configuration items need to be added
- Fetch has no way to natively monitor the progress of requests, whereas XHR can
To be honest, Fetch is not as easy to use as AXIos and jquery Ajax, but “cross-domain processing” Fetch performs much better than XHR. Due to the constraints of the same origin policy, requests sent by the browser cannot be randomly cross-domain, and must be assisted by JSONP or cross-domain header. Fetch can be directly set to “no-cors” to achieve cross-domain access, as shown below:
fetch('/login.json', {
method: 'post',
mode: 'cors',
data: {name:martin''}
}).then(function() { /* handle response */ });
Copy the code
We will get a response with type “opaque”. The request actually arrived in the background, but the browser cannot access the returned content, which is why the type in response is “opaque”.
In summary, Fetch is still a semi-finished product in a new era, and many places are not perfect, but it also has its advantages. In general, Fetch technology still needs time to precipitation, and it has not reached the performance of AXIOS.
The difference between Ajax, AXIos, and FETCH
Moving Documents 2: Handwriting Axios core principles