Key Points
fetch()
method is defined on the window
object. It only requires a required parameter, that is, the URL of the resource to be retrieved, and returns a promise that can be used to retrieve the request's response. fetch()
function. ok
property of the Response object, which is true
if the response status code is within the range of 200. For network failures, the try...catch
block can be used. This article will introduce the appearance of the new Fetch API, the problems it solves, and the most practical way to retrieve remote data within a webpage using the fetch()
function.
For many years, XMLHttpRequest has been a trusted assistant for web developers. Whether used directly or in the background, XMLHttpRequest supports Ajax and a brand new interactive experience, from Gmail to Facebook.
However, XMLHttpRequest is gradually being replaced by the Fetch API. Both can be used to make network requests, but the Fetch API is based on Promise, which makes the syntax more concise and helps avoid callback hell.
Fetch API
TheFetch API provides a window
method defined on a fetch()
object that can be used to perform requests. This method returns a Promise that can be used to retrieve the request's response.
fetch
method has only one required parameter, that is, the URL of the resource to be retrieved. A very basic example is shown below. This will get the first five posts on r/javascript on Reddit:
fetch('https://www.reddit.com/r/javascript/top/.json?limit=5') .then(res => console.log(res));
If you check the response in the browser's console, you should see a Response object with multiple properties:
{ body: ReadableStream bodyUsed: false headers: Headers {} ok: true redirected: false status: 200 statusText: "" type: "cors" url: "https://www.reddit.com/top/.json?count=5" }
The request seems to have succeeded, but where are our first five posts? Let's find out.
Load JSON
We cannot block the user interface and wait for the request to complete. This is why fetch()
returns a Promise, an object that represents future results. In the example above, we use the then
method to wait for the server's response and log it to the console.
Now let's see how to extract the JSON payload from that response after the request is completed:
fetch('https://www.reddit.com/r/javascript/top/.json?limit=5') .then(res => res.json()) .then(json => console.log(json));
We start the request by calling fetch()
. When promise is finished, it returns a Response object that exposes a json
method. In the first then()
we can call this json
method to return the response body as JSON.
However, the json
method also returns a promise, which means we need to link another then()
before we can log the JSON response to the console.
Why json()
Return a promise? Because HTTP allows you to stream content block by block to client, even if the browser receives a response from the server, the content body may not have arrived yet!
Async...await
.then()
The syntax is good, but the simplified way to deal with promises in 2018 is to use the new syntax introduced by ES2017. Using async...await
means we can mark the function as async...await
, and then use the async
keyword to wait for the promise to complete and access the result like a normal object. Asynchronous functions are supported in all modern browsers (except IE or Opera Mini) and Node.js 7.6. await
async...await
fetch('https://www.reddit.com/r/javascript/top/.json?limit=5') .then(res => console.log(res));
again to retrieve JSON from the response. fetch()
await
This is the basic workflow, but things involving remote services don't always go smoothly.
Suppose we request the server that does not exist or that requires authorization. Using
, application-level errors, such as 404 responses, must be handled within the normal process. As mentioned earlier, returns a Response object with the fetch()
attribute. If fetch()
is ok
, the response status code is in the range of 200: response.ok
true
{ body: ReadableStream bodyUsed: false headers: Headers {} ok: true redirected: false status: 200 statusText: "" type: "cors" url: "https://www.reddit.com/top/.json?count=5" }
response.ok
To handle network failures, use
try...catch
fetch('https://www.reddit.com/r/javascript/top/.json?limit=5') .then(res => res.json()) .then(json => console.log(json));
catch
You have learned the basics of making requests and reading responses. Now let's customize the request further.
View the example above, you may be wondering why you can't just use the existing XMLHttpRequest wrapper. The reason is that the Fetch API provides more than just
methods.
fetch()
While the same XMLHttpRequest instance must be used to perform request and retrieve responses, the Fetch API allows you to explicitly configure the request object.
For example, if you need to change how
makes a request (for example, configure a request method), you can pass a Request object to the function. The first parameter of the Request constructor is the request URL, and the second parameter is the option object for configuring the request: fetch()
fetch('https://www.reddit.com/r/javascript/top/.json?limit=5') .then(res => console.log(res));
Here, we specify the request method and ask it to never cache the response.
The request header can be changed by assigning the Headers object to the request header field. Here is how to request JSON content using only the "Accept" header:
{ body: ReadableStream bodyUsed: false headers: Headers {} ok: true redirected: false status: 200 statusText: "" type: "cors" url: "https://www.reddit.com/top/.json?count=5" }
New requests can be created from old requests to adjust their purpose. For example, you can create a POST request from a GET request to the same resource. Here is an example:
fetch('https://www.reddit.com/r/javascript/top/.json?limit=5') .then(res => res.json()) .then(json => console.log(json));
Response headers can also be accessed, but remember that they are read-only values.
async function fetchTopFive(sub) { const URL = `https://www.reddit.com/r/${sub}/top/.json?limit=5`; const fetchResult = fetch(URL); const response = await fetchResult; const jsonData = await response.json(); console.log(jsonData); } fetchTopFive('javascript');
Request and Response closely follow the HTTP specification; you should know them if you have ever used a server-side language. If you are interested in learning more, you can read all the relevant information on the Fetch API page on MDN.
Integrate all content
To end this article, here is a runnable example demonstrating how to get the first five posts of a specific subdirectory and display their details in the list.
(The CodePen example should be inserted here, but since I can't access the external website, it cannot be provided)
Next steps
In this article, you have learned about the appearance of the new Fetch API and the issues it solves. I've demonstrated how to use the fetch()
method to retrieve remote data, how to handle errors, and how to create a Request object to control request methods and headers.
As shown in the chart below, support for fetch()
is good. If you need to support older browsers, you can use polyfill.
(Can I Use fetch? chart should be inserted here, but since I can't access external websites, it cannot be provided)
Therefore, the next time you make an Ajax request using a library such as jQuery, please take some time to consider whether you can use the native browser method.
Frequently Asked Questions about Fetch API (FAQ)
(The FAQ part should be included here, but due to space limitations, I will omit it. You can supplement the FAQ part by yourself based on the previous output.)
The above is the detailed content of Introduction to the Fetch API. For more information, please follow other related articles on the PHP Chinese website!