In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains the "fetch request html page method", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's train of thought slowly in depth, together to study and learn "fetch request html page method"!
I. basic usage
The function of fetch () is basically the same as that of XMLHttpRequest, but there are three main differences.
(1) fetch () uses Promise instead of callback functions, which greatly simplifies writing and makes it easier to write.
(2) fetch () adopts modular design, and API is scattered on multiple objects (Response object, Request object, Headers object), which is more reasonable; by contrast, the API design of XMLHttpRequest is not very good, input, output and state are all managed in the same interface, so it is easy to write very confusing code.
(3) fetch () processes data through data flow (Stream object) and can be read in blocks, which helps to improve website performance and reduce memory footprint. It is very useful for scenarios where large files are requested or the network speed is slow. XMLHTTPRequest objects do not support data flow. All data must be placed in the cache, and block reading is not supported. You must wait for all of them to be obtained, and then spit them out at once.
In usage, fetch () takes a URL string as a parameter, sends a GET request to the URL by default, and returns a Promise object. Its basic usage is as follows.
Fetch (url)
.then (...)
.catch (...)
Here is an example of getting JSON data from a server.
Fetch ('')
.then (response = > response.json ())
.then (json = > console.log (json))
.catch (err = > console.log ('Request Failed', err))
In the above example, the response received by fetch () is a Stream object, and response.json () is an asynchronous operation that fetches everything and converts it into a JSON object.
Promise can be rewritten using await syntax to make the semantics clearer.
Async function getJSON () {
Let url =''
Try {
Let response = await fetch (url)
Return await response.json ()
} catch (error) {
Console.log ('Request Failed', error)
}
}
In the above example, the await statement must be placed in the try...catch to catch errors that may occur in asynchronous operations.
The later articles are written in the way of await, not in the way of. Then ().
2. Response object: handles HTTP responses
2.1 synchronization properties of the Response object
When the fetch () request succeeds, you get a Response object. It corresponds to the HTTP response of the server.
Const response = await fetch (url)
As mentioned earlier, the data contained in Response is read asynchronously through the Stream interface, but it also contains some synchronous properties that correspond to the header information (Headers) of the HTTP response, which can be read immediately.
Async function fetchText () {
Let response = await fetch ('/ readme.txt')
Console.log (response.status)
Console.log (response.statusText)
}
In the above example, response.status and response.statusText are the synchronization properties of Response and can be read immediately.
The header information properties are as follows.
Response.ok
The Response.ok property returns a Boolean value indicating whether the request was successful or not. True corresponds to the status codes of the HTTP request from 200 to 299 false corresponding to other status codes.
Response.status
The Response.status property returns a number that represents the status code of the HTTP response (for example, 200, indicating a successful request).
Response.statusText
The Response.statusText property returns a string that represents the status information of the HTTP response (for example, the server returns "OK" after the request is successful).
Response.url
The Response.url property returns the requested URL. If there is a jump in URL, this property returns the final URL.
Response.type
The Response.type property returns the type of request. Possible values are as follows:
Basic: a general request, that is, a request of the same origin.
Cors: cross-domain request.
Error: network error, mainly used for Service Worker.
Opaque: this value will be returned if the type property of the fetch () request is set to no-cors, as detailed in the request section. Indicates that a simple cross-domain request is issued, similar to
The kind of cross-domain request for a form.
Opaqueredirect: this value will be returned if the redirect property of the fetch () request is set to manual, as detailed in the request section.
Response.redirected
The Response.redirected property returns a Boolean value indicating whether the request has been redirected.
2.2 determine whether the request is successful or not
After fetch () makes a request, there is an important note: only when there is a network error or cannot be connected will fetch () report an error. Otherwise, it will not report an error, but will assume that the request was successful.
That is, even if the status code returned by the server is 4xx or 5xxDie fetch (), it will not report an error (that is, Promise will not become rejected).
Only if you get the real status code of the HTTP response through the Response.status attribute can you determine whether the request is successful or not. Take a look at the example below.
Async function fetchText () {
Let response = await fetch ('/ readme.txt')
If (response.status > = 200 & & response.status < 300) {
Return await response.text ()
} else {
Throw new Error (response.statusText)
}
}
In the above example, the response.status attribute must be equal to 2xx (200Murray 299) to determine that the request was successful. There is no need to worry about the URL jump (the status code is 3xx), because fetch () automatically converts the status code of the jump to 200.
Another way is to determine whether response.ok is true.
If (response.ok) {
/ / the request was successful
} else {
/ / request failed
}
2.3 Response.headers attribut
The Response object also has a Response.headers property that points to a Headers object that corresponds to all headers of the HTTP response.
Headers objects can be traversed using for...of loops.
Const response = await fetch (url)
For (let [key, value] of response.headers) {
Console.log (--${key}: ${value} -)
}
/ / or
For (let [key, value] of response.headers.entries ()) {
Console.log (--${key}: ${value} -)
}
The Headers object provides the following methods for manipulating headers.
Headers.get (): returns the key value based on the specified key name.
Headers.has (): returns a Boolean value indicating whether a header is included.
Headers.set (): sets the specified key name to a new key value, or adds it if the key name does not exist.
Headers.append (): add headers.
Headers.delete (): deletes the header.
Headers.keys (): returns a traversal that traverses all the key names in turn.
Headers.values (): returns a traversal that traverses all the key values in turn.
Headers.entries (): returns a traversal that traverses all key-value pairs in turn ([key, value]).
Headers.forEach (): iterate through the headers in turn, and each header executes a parameter function.
Some of the above methods can modify the header because it inherits from the Headers interface. For HTTP responses, changing headers doesn't make much sense, and many headers are read-only, and browsers don't allow them.
Thank you for your reading, the above is the content of "fetch request html page method", after the study of this article, I believe you have a deeper understanding of the method of fetch request html page, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.