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】
1. 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) . 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.
2. Cross-origin resource sharing
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.
3. Preflight request
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;
4. Fetch API
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
套接字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思维导图

【相关推荐: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!
JavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AMJavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.
JavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AMThe main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft







