Home >Web Front-end >JS Tutorial >JavaScript detailed analysis of network requests and remote resources
This article brings you relevant knowledge about javascript, which mainly introduces issues related to network requests and remote resources, including cross-origin resource sharing, preflight requests, and Fetch API Let’s take a look at the content below. I hope it will be helpful to everyone.
[Related recommendations: javascript video tutorial, web front-end】
In 2005, Jesse James Garrett wrote an article "Ajax - A New Approach to Web Applications", which described a technology called Ajax (Asynchronous JavaScript XML) . 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 to 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 tools.
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, Cross-Origin Resource Sharing) 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. This behavior will be automatically triggered when trying to access resources from different sources. To send a request to a source 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 <p> Cross-domain XHR objects allow access to the status and statusText properties, and also allow synchronous requests , cross-domain XHR objects also impose some additional restrictions for security reasons. </p>
Cannot use setRequestHeader() to set custom headers;
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 to use relative when accessing local resources. URL, use absolute URL when accessing remote resources, which can more clearly distinguish usage scenarios and avoid the problem of restricted access to header or cookie information when accessing local resources.
CORS allows the use of custom headers, methods other than GET and POST, and different request bodies through a server verification mechanism called preflight request. Content type. 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: Same as a simple request;
Access-Control-Request-Method : The method you want to use for the request;
Access-Control-Request-Headers: (Optional) A comma-separated list of custom headers to use;
The Fetch API can perform all the tasks of the XMLHttpRequest object, but is easier to use, has a more modern interface, 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 contract:
let r = fetch('/bar');console.log(r);//Promise<pending></pending>
URL的格式(相对路径、绝对路径等)的解释与XHR对象一样。
请求完成、资源可用时,期约会解决一个Response对象,这个对象是API的封装,可以通过它取得相应资源。获取资源要使用这个对象的属性和方法,掌握响应的情况并将负载均衡转为有用的形式。
2、读取响应
读取响应内容的最简单方式是取得纯文本格式的内容,只要用到text()方法。这个方法返回一个期约,会解决为取得资源的完整内容。
3、处理状态码和请求失败
Fetch API 支持通过Response的status和statusText属性检查响应状态。成功获取响应的请求通常会产生值为200的状态码。
4、常见Fetch请求模式
发送JSON数据
在请求体中发送参数
发送文件
加载Blob文件
发送跨域请求
中断请求
套接字websocket的目标是通过一个长时连接实现与服务器全双工、双向的通信。在JavaScript中创建websocket时,一个HTTP请求会发送到服务器以初始化连接。服务器响应后,连接使用HTTP中的Upgrade头部从HTTP协议切换到websocket协议,这意味着websocket不能通过标准HTTP服务器实现,而必须使用支持该协议的专有服务器。
因为websocket使用了自定义协议,所以URL方案稍有变化,不能再使用http://或https://,而要使用ws://和wss://。前者是不安全的连接,后者是安全连接。在执行websocket URL时,必须包含URL方案,因为将来有可能再支持其他方案。
使用自定义协议而非HTTP协议的好处是,客户端与服务器质检可以发送非常少的数据,不会对HTTP造成任何负担。使用更小的数据包让websocket非常适合宽带和延迟问题比较明显的移动应用。使用自定义协议的缺点是,定义协议的时间比定义JavaScript API的时间要长,websocket得到了所有主流浏览器的支持。
【相关推荐:javascript视频教程、web前端】
The above is the detailed content of JavaScript detailed analysis of network requests and remote resources. For more information, please follow other related articles on the PHP Chinese website!