Before we learn about Ajax, we need to understand an object.

The XMLHttpRequest object

The XMLHttpRequest object is the core of the browser request. The object provides full access to the HTTP protocol. It is used to request or send data, which can be returned to the Web server synchronously or asynchronously.

It is supported by all browsers, however, in IE 5 and IE 6, the IE-specific ActiveXObject() constructor must be used.

Create a simple XMLHttpRequest object:

// Older versions of Internet Explorer (IE5 and IE6) use ActiveX objects
let xhr = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('post',url,true)
xhr.send('hello')
xhr.onreadystatechange = function() {
    if(xhr.readyState == 4 && xhr.status == 200) {console.log('hello')}}Copy the code

attribute

  • readyState: Indicates the status of the HTTP request. When aXMLHttpRequestThe value of this property starts at 0 when it is first created and increases to 4 when a full HTTP response is received. The status is as follows:
    • 0: indicates initialization.XMLHttpRequestObject has been created or has been createdabort()Method reset.
    • 1:open()Method has been called, butsend()Method is not called. The request has not been sent yet.
    • 2:Send()Method is invoked and the HTTP request is sent to the Web server. No response was received.
    • 3: All response headers have been received. The response body began receiving but did not complete.
    • 4: The HTTP response has been received.

ReadyState is not decremented unless the abort() or open() methods are called during a request process. The onReadyStatechange event handle is triggered each time the value of this property is increased.

  • ResponseText: The body (excluding the header) of the response received by the server so far, as a string, or an empty string if no data has been received.

  • ResponseXML: response body in XML form.

  • Status: HTTP status code returned by the server. For example, 200 indicates success.

The event

  • onreadystatechange: Receives server response data wheneverreadyStateThe event is called when the value of this property changes.

methods

open(method,url,async,username,password)

Initializes the HTTP request.

  • methodsRequest methods, including GET,POST, and HEAD.
  • url: Request body. Most browsers enforce a same-origin security policy and require this URL to have the same host name and port as the text containing the script.
  • async: indicates that request usage should be executed asynchronously. If this parameter isfalse, requests are synchronous, subsequent pairssend()Will block until the response is fully received. If this parameter istrueOr omit, the request is asynchronous and usually requires oneonreadystatechangeEvent handle.
  • The username and password parameters are optional and provide authentication for the authorization required for the URL.

send(body)

Send an HTTP request. The request consists of the following parts:

  • The HTTP method, URL, and authentication qualification (if any) specified earlier when open() was called.

  • The request header (if any) specified earlier when setRequestHeader() was called.

  • The body argument passed to this method.

The body argument specifies the request body as a string or Document object. This parameter is null if the request body is not required.

If open() has not been called before, or more specifically, if readyState is not 1, send() throws an exception.

If the open() async argument called earlier was false, this method blocks and does not return until readyState is 4 and the server response is fully received. If async is true, send() returns immediately.

Once the request is published, send() sets readyState to 2 and fires the onReadyStatechange event handle.

setRequestHeader(name, value)

  • The name parameter is the name of the header to be set. This parameter should not include whitespace, colons, or line breaks.
  • The value argument is the value of the header. This parameter should not include a newline.

The setRequestHeader() method specifies the header of an HTTP request that should be included in the request published through subsequent send() calls. This method can only be called if readyState is 1

If a header with the specified name is already specified, the new value for the header is the previously specified value, plus a comma, whitespace, and the value specified by the call.

The difference between get and POST requests

  • GET has no effect when the browser back backs back, whereas POST resubmits the request.

  • The URL generated by GET can be marked, but POST cannot.

  • GET requests are actively cached by browsers, whereas POST is not, unless set manually.

  • GET requests can only be url encoded, while POST supports multiple encoding methods.

  • GET request parameters are retained in browser history, while parameters in POST are not.

  • GET requests pass parameters in the URL with length limits, whereas POST does not.

  • The GET argument is passed through the URL, and the POST is placed in the Request body.

  • GET accepts only ASCII characters for the data type of the argument, while POST has no restrictions.

  • GET is less secure than POST because parameters are exposed directly to the URL and therefore cannot be used to pass sensitive information.

AJAX

Ajax is what?

Asynchronous is an acronym for JavaScript and XML and refers to a development technique for creating dynamic, interactive web pages. Data can be sent asynchronously & requests without the need to refresh the current page.

What is ajax for?

The function is to improve user experience and reduce network data transmission.

Technical Architecture of Ajax (Principles)

  • Based on thewebstandardXHTML+CSSThe representation of the
  • useDOMDynamic display and interaction
  • useXMLandXSLTPerform data exchange and related operations
  • useXMLHttpRequestPerform asynchronous data query and retrieval
  • useJavaScriptBind everything together

What is XML?

Full name: EXtensible Markup Language

Hyper Text Markup Language> HTML is used to format and display data.

  • Extensible markup language

  • Used to transfer and store data.

  • XML is just plain text

  • XML doesn’t do anything.

  • XML is a complement to HTML

Ajax encapsulation

From the above principles, we can simply wrap an Ajax:


// Format parameters
function formateData(data){
    let arr = []
    for(let key in data){
        arr.push(encodeURIComponent(key) + '=' + data[key])
    }
    reutrn arr.join('&')}function ajax(params){
    params = params || {}
    params.data = params.data || {}
    
    params.type = { params.type || 'GET' }.toUpperCase()
    params.data = formateData(params.data)
   let xhr = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
   if(params.type === 'GET'){
       xhr.open(params.type, params.url+'? '+params.data, true)
       xhr.send()
   } else {
       xhr.open(params.type, params.url, true)
       xhr.setRequestHeader("Content-type"."application/x-www-form-urlencoded")
       xhr.send(params.data)       
   }
   xhr.onreadystatechange = function() {
      if(xhr.readyState == 4) {if(xhr.status == 200 || xhr.status == 304 || xhr.status == 206)
            if (params.success && params.success instanceof Function) {
                res = JSON.parse(xhr.responseText); params.success.call(xhr, res); }}else {
            if (params.error && params.error instanceof Function) {
                res = xhr.responseText;
                params.error.call(xhr, res);
            }
       }
    }   
}

ajax({
    type:'POST'.url:' '.data: {name:'yang'
    },
    success:function(res){},
    error:function(err){},})Copy the code

Ajax request steps

From the above, you can analyze the steps of Ajax:

  • Create an XMLHttpRequest object

  • Register the callback function onreadyStatechange

  • Use open() to initialize the request information and configure the request header

  • Use send() to send the request information

  • Create a callback function that receives the data returned by the server and responds to the page.

Callback for ajax requests

  • onSuccess
  • onFailure
  • onUninitialized
  • onLoading
  • onloaded
  • onInteractive
  • onComplete
  • onException

Differences between Ajax and traditional Web applications

Traditional Web applications: Traditional Web applications use forms to fetch or send data, and when you click submit, send the data, and then wait for the server to respond to the request, the server will return a new page and the page will reload, which is not very user friendly.

Ajax: Interacts with the server through an XMLHttpRequest object. The XMLHttpRequest object can accept the information returned by the server and modify the page data without reloading the page. If the request is asynchronous, it will not block the load.

Advantages and disadvantages of Ajax

Advantages:

  • Data is updated asynchronously without refreshing, improving user experience.
  • Optimized transfer between browser and server, more responsive.
  • Ajax runs on the client side and takes over some of the server’s work, reducing the burden on the server.

Disadvantages:

  • Ajax does not support the browser back button
  • Ajax exposes the details of the interaction with the server
  • Search engine support is weak
  • Not easy to debug

Axios

What is a axios?

Axios is a Promise based HTTP library that can be executed in a browser or node environment.

What are axios’s features (advantages)?

  • Asynchronous requests based on promises
  • It can be used on both the browser side and the Node side, where the browser creates an XMLHttpRequest and node creates an HTTP request.
  • Support for request/response interception
  • Support request cancellation
  • Request data and response data can be transformed
  • Multiple requests can be sent in batches
  • High security and XSRF defense.

XSRF: Cross-domain request forgery. In AXIos, each request carries a key obtained from a cookie. The fake website cannot obtain the key from the cookie based on the browser’s same source. This allows the backend to easily identify whether the request is a misleading input from the user on the fake website and take the correct policy source.

What are ajax’s disadvantages compared to AXIos?

  • Itself is for MVC mode of programming, does not conform to the current MVVM mode.
  • Based on native XHR development, the architecture of XHR itself is unclear.
  • Does not conform to the principle of separation of concerns.
  • Configuration and invocation are messy, and the event-based asynchronous model is unfriendly.

Axios grammar

axios({
  method: 'post'.url: '/user/12345'.data: {
    firstName: 'Fred'.lastName: 'Flintstone'
  }
}).then((a)= >{})

axios.get('http://127.07.01',config).then((a)= >{})
// It is important to note that if the get request is to pass parameters, it needs to be written in config
axios.get('http://127.07.01', {params:data
}).then((a)= >{})

axios.post('http://127.07.01',params,config).then((a)= >{})

Copy the code

Common syntax

  • Axios (config) : general
  • Axios (url,[config]): You can specify the URL to send a GET request
  • Axios. Request (config) : equal axios (config)
  • Axios. Get (url, / config) : get request
  • Axios. Post (url, / data and config) : a post request
  • Axios. Put (url, / data and config) : put request
  • Axios.default. XXX: the default global configuration
  • Axios. Interceptors. Request. Use () : request interceptor
  • Axiox. Interceptors. Responese. Use () : response interceptors
  • Axios.create ([config]): Creates a new axios
  • axios.Cancel():
  • Axios.all (promise): Used to batch execute multiple asynchronous requests
  • Axios.spread (): Specifies the method for the callback function that receives all success data.

Some axios features

The entrance

  • Create an instance, bind the prototype method in Axios, and point this to Axios.
var defaults = require('./defaults');
function createInstance(defaultConfig) {
  // An instance of Axios is created here
  var context = new Axios(defaultConfig);
  var instance = bind(Axios.prototype.request, context);
  // This uses the bind method to change the direction of axios.prototype. request, this, to return the new function;
  module.exports = function bind(fn, thisArg) {
  return function wrap() {
    var args = new Array(arguments.length);
    for (var i = 0; i < args.length; i++) {
      args[i] = arguments[i];
    }
    return fn.apply(thisArg, args);
  };
};
var axios = createInstance(defaults);
Copy the code

The default configuration

  • Determine the current environment
  • Some configuration of the request header
    • Url: the url of the requested server
    • Headers: request head
    • TransformRequest: Allows you to modify request data before sending it to the server. This can only be used in the ‘PUT’,’POST’, and ‘PATCH’ request methods
    • Method: request method
    • Params: request parameters
    • Auth: authentication
  • When you have a custom configuration, use the merge method to replace the default configuration with the custom one

// This is how Axios supports browsers and Nodes
function getDefaultAdapter() {
  var adapter;
  if (typeofXMLHttpRequest ! = ='undefined') {
    // The chess browser uses XMLHttpRequest
    adapter = require('./adapters/xhr');
  } else if (typeofprocess ! = ='undefined') {
    // Node uses HTTP
    adapter = require('./adapters/http');
  }
  return adapter;
}

 var defaults = {
     adapter:getDefaultAdapter(),
 }
 
 defaults.headers = {
  common: {
    'Accept': 'application/json, text/plain, */*'}}; utils.forEach(['post'.'put'.'patch'].function forEachMethodWithData(method) {
  defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
});


Copy the code

Browser implementation

  • Run the xhr.js module when the current environment is a browser
  • Xhr.js returns a Promise object, which is createdXMLHttpRequestObject, which calls promise’s resolve on success and Reject on failure.
  • Implement axios cancel request

function xhrAdapter(config) {
 return new Promise(function dispatchXhrRequest(resolve,reject) = >{
     var request = new XMLHttpRequest();
     request.onreadystatechange = function handleLoad() {
       if(! request || request.readyState ! = =4) {
        return;
      }
      if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') = = =0)) {
        return;
      }
      // ...
      settle(resolve, reject, response);
      request = null;
     }
     // Where to cancel the request
    if (config.cancelToken) {
      config.cancelToken.promise.then(function onCanceled(cancel) {
        if(! request) {return;
        }

        request.abort();
        reject(cancel);
        // Clean up request
        request = null;
      });
    }
    if (requestData === undefined) {
      requestData = null;
    }
    // Send the requestrequest.send(data); })}Copy the code

Core method Request ()

  • Mount methods like GET, POST, and so on to the prototype.
  • Get, PUT,post, and request() are all called
  • Before the request is sent, there is an array chain. The functions intercepted by the request are added to the front of the array. After the request, the functions are loaded to the back of the array, and the array is called in order.
Axios.prototype.request = function request(config) {
  var chain = [dispatchRequest, undefined];
  // Request interception
  this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
    chain.unshift(interceptor.fulfilled, interceptor.rejected);
  });
  // Response interception
   this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
    chain.push(interceptor.fulfilled, interceptor.rejected);
  });
  // Loop through all methods
  while (chain.length) {
    promise = promise.then(chain.shift(), chain.shift());
  }
  return promise;
}
Copy the code

The interceptor

The handles array collects all interceptor methods

Role?

  • Loading is turned on when the interceptor is requested and the response interceptor is turned off.
  • A unified toast pops up for requests when errors occur
  • The response interceptor processes the response data format uniformly or separately

Axios cancels

For the cancellation request, the cancelToken object is passed in when axios is created. This object creates a promise and exposes a cancellation method. When the cancellation method is called, the promise state is set to success. Request.abort () is called in the XHR file.

Axios is used in Vue

Use in main.js


import axios from 'axios'

/* Request interceptor */
axios.interceptors.request.use(
	config= > {
		let token = localStorage.getItem('userToken')
		if (token) {
			config.headers.token = token
		}
		// config.url = process.env.NODE_ENV === 'production' ? apiMode.SERVICE_CONTEXT_PATH + config.url : 'apis' + config.url
		// config.url = apiMode.SERVICE_CONTEXT_PATH + config.url
		return config
	},
	error => {
		return Promise.reject(error)
	}
)
/** * axios interceptor, background response whether need to log in again */
axios.interceptors.response.use(
	response= > {
		if (response) {
			switch (response.data.code) {
				case 11001:
					login()
					break
				case 10004:
					login()
					break}}return response
	},
	error => {
		return Promise.reject(error.response.data) // Return the error message returned by the interface
	}
)
axios.defaults.withCredentials = true
axios.defaults.crossDomain = true
Copy the code

Extended questions

Why can axios be used both as a function call and as an object, such as axios({}), axios.get?

Axios is essentially a function, but it has alias methods that refer to the same method axios.request().

utils.forEach(
 ["delete"."get"."head"."options"].function forEachMethodNoData(method) {
   Axios.prototype[method] = function(url, config) {
     return this.request(
       utils.merge(config || {}, {
         method: method,
         url: url }) ); }; }); utils.forEach(["post"."put"."patch"].function forEachMethodWithData(method) {
 Axios.prototype[method] = function(url, data, config) {
   return this.request(
     utils.merge(config || {}, {
       method: method,
       url: url,
       data: data
     })
   );
 };
});
Copy the code

Why do you support sending requests from browsers and Node?

Axios sends the request on the browser side using the XMLHttpRequest object; Requests are sent using HTTP objects in the Node environment.

var defaults.adapter = getDefaultAdapter();
function getDefaultAdapter () {
	var adapter;
    if (typeofXMLHttpRequest ! = ='undefined') {
    	// Browser environment
        adapter = require('./adapter/xhr');
    } else if (typeofprocess ! = ='undefined') {
    	/ / the node environment
        adapter = require('./adapter/http');
    }
   return adapter;
}
Copy the code

fetch

fetch(url).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
}).catch(function(e) {
  console.log("Oops, error");
});
Copy the code

Characteristics of the fetch?

  • Syntax concise, more semantic

  • Support async/await based on standard Promise implementation

  • Isomorphic-fetch is used for convenient isomorphism

Isomorphic /universal means that the same set of code is run on the front and back ends, and the back end generally refers to the NodeJS environment

The fetch attention

  • Fetch (URL, {credentials: ‘include’})
  • The server does not reject 400,500 error codes, and the fetch is rejected only when network errors such as these cause the request to be unable to complete.
  • All versions of IE do not support native Fetch

Relevant extended questions

What is the difference between Ajax, Fetch, and Axios?

  • Ajax is a technology based on xmlHttpRequest.

  • Fetch is an API, based on Promise, that addresses xmlHttpRequest’s unfocused separation, messy invocation, and optimized asynchronous model

  • Axios is a third-party library wrapped based on xmlHttpRequest+ Promise

The HTTP status code

Only some representative status codes are identified:

  • 200 indicates that the request from the client is processed on the server.

  • 204 indicates that the request was processed successfully, but no resources were returned.

  • 301 indicates a permanent redirect. This status code indicates that the requested resource has been assigned a new URI and that the URI to which the resource now refers should be used later.

  • 302 represents a temporary redirect.

  • 304 When the client sends a conditional request (the request message using the GET method contains if-matched,if-modified-since,if-none-match,if-range, and if-unmodified-since headers), the server allows the request to access the information Source, but returns 304Modified because the request does not meet the condition.

  • 400 indicates that syntax errors exist in the request packet. When an error occurs, you need to modify the content of the request and send the request again.

  • 401 indicates that the request is Unauthorized and requires user authentication

  • 403 indicates that access to the requested resource was denied by the server

  • 404: The requested resource could not be found on the server. In addition, it can be used when the server rejects the request without giving a reason.

  • 500 indicates that an error occurred on the server side while executing the request. It could also be a Web application bug or some temporary glitch.

  • 503 indicates that the server is temporarily overloaded or is down for maintenance and is unable to process requests.