In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Today, the editor will share with you the relevant knowledge points about the methods of JavaScript network requests and remote resources. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look.
First, the birth of Ajax
In 2005, Jesse James Garrett wrote an article, "Ajax-A New Approach to Web Applications," which described a technology called Ajax (Asynchronous JavaScript+XML, or Asynchronous JavaScript+XML). This technique involves sending the server to request additional data without refreshing the page to achieve a better user experience. Garrett explains how this technology has changed the traditional click-and-wait pattern that has been going on since the birth of Web.
The key technology that pushes Ajax to the stage of history is the XMLHttpRequest (XHR) object. Before XHR, Ajax-style communication had to be achieved through some cool techs, mainly using hidden panes or embedded panes. XHR provides a reasonable interface for sending server requests and getting corresponding. This interface allows you to get extra data asynchronously from the server, meaning that users can get data without page refresh. After you get the data through the XHR object, you can use the DOM method to insert the data into the web page.
API of XHR object is generally considered to be difficult to use, and Fetch API has quickly become a more modern alternative standard for XHR after its automatic birth. Fetch API supporting promise and service thread (service worker) has become a powerful Web development tool.
II. Cross-source resource sharing
One of the main limitations of Ajax communication over XHR is cross-source security policies. By default, XHR can only access resources in the same domain as the page that initiated the request. This security restriction can prevent some malicious behavior. However, browsers also need the ability to support legitimate cross-source access.
Cross-source resource sharing (CORS,Cross-Origin Rerource Sharing) defines how browsers and servers communicate across sources. The basic idea behind CORS is to use custom HTTP headers to allow browsers and servers to learn about each other to determine whether the request or corresponding should succeed or fail.
For simple requests, such as GET or POST requests, where there is no custom header and the request body is of type text/plain, such a request will be sent with an additional header called Origin. The Origin header contains the source (protocol, domain name, port) of the page that sent the request, so that the server can determine whether to provide a response for it.
Modern browsers natively support CORS through XMLHttpRequst objects, and this behavior is automatically triggered when trying to access resources from different sources. To send a request to a source in a different domain, use the standard XHR object and pass an absolute URL to the open () method, such as:
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 the status and statusText properties, as well as synchronous requests, and for security reasons, cross-domain XHR objects impose some additional restrictions.
Cannot use setRequestHeader () to set custom headers
Cannot send and receive cookie
The getAllResponseHeaders () method always returns an empty string
Because both intra-domain and cross-domain requests use the same interface, it is best to use relative URL when accessing local resources and absolute URL when accessing remote resources, so as to distinguish usage scenarios more clearly and avoid the problem of limited header or cookie information access when accessing local resources.
III. Pre-inspection request
CORS allows the use of custom headers, methods other than GET and POST, and different request body content types through a server authentication mechanism called pre-check requests. When you want to send a request involving one of these advanced options, a pre-check request is sent to the server first. The request is sent using the OPTIONS method and contains the following headers:
Origin: same as simple request
Access-Control-Request-Method: request the method you want to use
Access-Control-Request-Headers: (optional) comma-separated list of custom headers to use
IV. Fetch API
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 Fetch API must be asynchronous.
The fetch () method is exposed to the global scope, including the main page execution thread, module, and worker thread. When this method is called, the browser sends a request to the given URL.
1. Dispatch request
Fetch () has only one required parameter, input. In most cases, this parameter is the URL that gets the resource, and this method returns a contract:
Let r = fetch ('/ bar'); console.log (r); / Promise
The format of URL (relative path, absolute path, and so on) is interpreted in the same way as XHR objects.
When the request is completed and the resource is available, the appointment resolves a Response object, which is an encapsulation of API, through which the corresponding resource can be obtained. To get a resource, use the properties and methods of this object, master the response, and turn load balancing into a useful form.
2. Read the response
The easiest way to read the response content is to get the content in plain text format, as long as the text () method is used. This method returns a contract that is resolved to get the full contents of the resource.
3. Failed to process status code and request
Fetch API supports checking the response status through the status and statusText properties of Response. A successful request to get a response usually produces a status code with a value of 200.
4. Common Fetch request modes
Send JSON data
Send parameters in the request body
Send a file
Load Blob Fil
Send cross-domain request
Interrupt request
5. Websocket
The goal of socket websocket is to achieve full-duplex, two-way communication with the server through a long-term connection. When a websocket is created in JavaScript, an HTTP request is sent to the server to initialize the connection. After the server responds, the connection uses the Upgrade header in HTTP to switch from the HTTP protocol to the websocket protocol, which means that websocket cannot be implemented through a standard HTTP server, but must use a proprietary server that supports the protocol.
Because websocket uses a custom protocol, the URL scheme has changed slightly, and instead of using http:// or https://, ws:// and wss:// can be used. The former is an insecure connection, and the latter is a secure connection. When you execute websocket URL, you must include the URL scheme, as other scenarios may be supported in the future.
The advantage of using custom protocols instead of HTTP protocols is that client and server quality checks can send very little data without any burden on HTTP. The use of smaller packets makes websocket very suitable for mobile applications where broadband and latency problems are obvious. The disadvantage of using custom protocols is that it takes longer to define a protocol than it takes to define JavaScript API, and websocket is supported by all major browsers.
These are all the contents of this article entitled "JavaScript Network requests and remote Resources". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.