In 2005, Jesse James Garrett wrote an article "Ajax - A New Approach to Web Applications", which described an application called Ajax (Asynchronous JavaScript+XML). technology. This technique involves sending the server a request for additional data without refreshing the page, resulting in a better user experience. Garrett explains how this technology changes the traditional click-and-wait model that has persisted since the birth of the Web.
The key technology that pushed Ajax onto the historical stage is the XMLHttpRequest (XHR) object. Before the advent of XHR, Ajax-style communication had to be achieved through some black technology, mainly using hidden panes or inline panes. XHR provides a reasonable interface for sending server requests and getting responses. This interface can obtain additional data from the server asynchronously, which means that users can obtain data without refreshing the page. After obtaining data through the XHR object, you can use DOM methods to insert the data into the web page.
The XHR object API is generally considered difficult to use, and the Fetch API quickly became a more modern alternative standard for XHR after its automatic birth. The Fetch API supports scheduled promises and service threads (service workers), and has become an extremely powerful web development tool. .
A major limitation of Ajax communication through XHR is the cross-origin security policy. By default, XHR can only access resources in the same domain as the page that initiated the request. This security restriction prevents certain malicious behavior. However, browsers also need to support legal cross-origin access.
Cross-Origin Resource Sharing (CORS) defines how browsers and servers implement cross-origin communication. The basic idea behind CORS is to use custom HTTP headers to allow the browser and server to understand each other to determine whether a request or response should succeed or fail.
For simple requests, such as GET or POST requests, there are no custom headers, and the request body is of text/plain type. Such requests will have an additional header called Origin when sent. The Origin header contains the source (protocol, domain name, port) of the page sending the request so that the server can determine whether to provide a response for it.
Modern browsers natively support CORS through the XMLHttpRequst object, which is automatically triggered when trying to access resources from different origins. To send a request to an origin in a different domain, you can use a standard XHR object and pass an absolute URL to the open() method, for example:
let xhr = new XMLHttpRequest();xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ alert(xhr.reaponseText); }else{ alert("Request was unsuccessful:"+xhr.status); } }};xhr.open("get","http://www.nezha.con/page/",true);xhr.send(null);
Cross-domain XHR objects allow access to status and statusText properties, and also allow synchronization Requests that cross-domain XHR objects also impose some additional restrictions for security reasons.
You cannot use setRequestHeader() to set custom headers;
you cannot send and receive cookies;
the getAllResponseHeaders() method always returns an empty string;
because the same interface is used for both same-domain and cross-domain requests, it is best when accessing local resources Use relative URLs and use absolute URLs when accessing remote resources. This can more clearly distinguish usage scenarios and avoid the problem of restricted access to header or cookie information when accessing local resources.
CORS uses a server verification mechanism called preflight request, allowing the use of custom headers, methods other than GET and POST, and different request body content types. When sending a request involving one of the above advanced options, a preflight request is first sent to the server. This request is sent using the OPTIONS method and contains the following headers:
Origin: the same as a simple request;
Access-Control-Request-Method: the method you want to use;
Access-Control-Request-Headers: (optional) comma-separated values to use Custom header list;
The Fetch API can perform all the tasks of the XMLHttpRequest object, but it is easier to use, the interface is more modern, and can be used in Web tools such as Web worker threads. XMLHttpRequest can choose to be asynchronous, while the Fetch API must be asynchronous.
The fetch() method is exposed in the global scope, including the main page execution thread, modules and worker threads. Calling this method causes the browser to send a request to the given URL.
1. Dispatch request
fetch() has only one required parameter input. In most cases, this parameter is the URL to obtain the resource, and this method returns a promise:
let r = fetch('/bar');console.log(r);//Promise<pending>
URL format (relative path, absolute paths, etc.) are interpreted the same as XHR objects.
When the request is completed and the resources are available, a Response object will be processed. This object is an encapsulation of the API through which the corresponding resources can be obtained. Use the properties and methods of this object to obtain resources, understand the response, and convert load balancing into a useful form.
2. Read the response. The simplest way to read the response content is to obtain the content in plain text format, just use the text() method. This method returns a promise, which resolves to retrieving the complete contents of the resource.
3. Handling status codes and request failures
The Fetch API supports checking the response status through the status and statusText properties of Response. Requests that successfully obtain a response usually produce a status code with a value of 200.
4. Common Fetch request modes:
Send JSON data,
send parameters in the request body,
send files
, load Blob files
, send cross-domain requests,
interrupt requests
socket The goal of websocket is to achieve full-duplex and two-way communication with the server through a long-term connection. communication. When creating a websocket in JavaScript, an HTTP request is sent to the server to initialize the connection. After the server responds, the connection switches from the HTTP protocol to the websocket protocol using the Upgrade header in HTTP, which means that websocket cannot be implemented through a standard HTTP server, but must use a proprietary server that supports this protocol.
Because websocket uses a custom protocol, the URL scheme has changed slightly. http:// or https:// can no longer be used, but ws:// and wss:// must be used. The former is an insecure connection and the latter is a secure connection. When executing websocket URLs, the URL scheme must be included as it is possible that additional schemes may be supported in the future.
The advantage of using a custom protocol instead of the HTTP protocol is that the client and server can send very little data without causing any burden on HTTP. Using smaller data packets makes websockets ideal for mobile applications where bandwidth and latency issues are significant. The disadvantage of using a custom protocol is that defining the protocol takes longer than defining the JavaScript API. Websocket is supported by all major browsers.