网页 综合 更新时间 2025-08-20 18:33:20

Using the Fetch API - Web APIs | MDN

自动蜘蛛 developer.mozilla.org 正文约 5803 字
HTML: Markup language
CSS: Styling language
JavaScript: Scripting language
Web APIs: Programming interfaces
Learn web development
Get to know MDN better
The Fetch API provides a JavaScript interface for making HTTP requests and processing the responses.
Fetch is the modern replacement for XMLHttpRequest: unlike XMLHttpRequest, which uses callbacks, Fetch is promise-based and is integrated with features of the modern web such as service workers and Cross-Origin Resource Sharing (CORS).
With the Fetch API, you make a request by calling fetch(), which is available as a global function in both window and worker contexts. You pass it a Request object or a string containing the URL to fetch, along with an optional argument to configure the request.
The fetch() function returns a Promise which is fulfilled with a Response object representing the server's response. You can then check the request status and extract the body of the response in various formats, including text and JSON, by calling the appropriate method on the response.
Here's a minimal function that uses fetch() to retrieve some JSON data from a server:
We declare a string containing the URL and then call fetch(), passing the URL with no extra options.
The fetch() function will reject the promise on some errors, but not if the server responds with an error status like 404: so we also check the response status and throw if it is not OK.
Otherwise, we fetch the response body content as JSON by calling the json() method of Response, and log one of its values. Note that like fetch() itself, json() is asynchronous, as are all the other methods to access the response body content.
In the rest of this page we'll look in more detail at the different stages of this process.
To make a request, call fetch(), passing in:
In this section we'll look at some of the most commonly-used options. To read about all the options that can be given, see the fetch() reference page.
By default, fetch() makes a GET request, but you can use the method option to use a different request method:
If the mode option is set to no-cors, then method must be one of GET, POST or HEAD.
The request body is the payload of the request: it's the thing the client is sending to the server. You cannot include a body with GET requests, but it's useful for requests that send content to the server, such as POST or PUT requests. For example, if you want to upload a file to the server, you might make a POST request and include the file as the request body.
To set a request body, pass it as the body option:
You can supply the body as an instance of any of the following types:
Other objects are converted to strings using their toString() method. For example, you can use a URLSearchParams object to encode form data (see setting headers for more information):
Note that just like response bodies, request bodies are streams, and making the request reads the stream, so if a request contains a body, you can't make it twice:
Instead, you would need to create a clone of the request before sending it:
See Locked and disturbed streams for more information.
Request headers give the server information about the request: for example, in a POST request, the Content-Type header tells the server the format of the request's body.
To set request headers, assign them to the headers option.
You can pass an object literal here containing header-name: header-value properties:
Alternatively, you can construct a Headers object, add headers to that object using Headers.append(), then assign the Headers object to the headers option:
Compared to using plain objects, the Headers object provides some additional input sanitization. For example, it normalizes header names to lowercase, strips leading and trailing whitespace from header values, and prevents certain headers from being set. Many headers are set automatically by the browser and can't be set by a script: these are called Forbidden request headers. If the mode option is set to no-cors, then the set of permitted headers is further restricted.
GET requests don't have a body, but you can still send data to the server by appending it to the URL as a query string. This is a common way to send form data to the server. You can do this by using URLSearchParams to encode the data, and then appending it to the URL:
Whether a request can be made cross-origin or not is determined by the value of the RequestInit.mode option. This may take one of three values: cors, same-origin, or no-cors.
For fetch requests the default value of mode is cors, meaning that if the request is cross-origin then it will use the Cross-Origin Resource Sharing (CORS) mechanism. This means that:
Setting mode to same-origin disallows cross-origin requests completely.
Setting mode to no-cors disables CORS for cross-origin requests. This restricts the headers that may be set, and restricts methods to GET, HEAD, and POST. The response is opaque, meaning that its headers and body are not available to JavaScript. Most of the time a website should not use no-cors: the main application of it is for certain service worker use cases.
See the reference documentation for RequestInit.mode for more details.
In the context of the Fetch API, a credential is an extra piece of data sent along with the request that the server may use to authenticate the user. All the following items are considered to be credentials:
By default, credentials are only included in same-origin requests. To customize this behavior, as well as to control whether the browser respects any Set-Cookie response headers, set the credentials option, which can take one of the following three values:
Note that if a cookie's SameSite attribute is set to Strict or Lax, then the cookie will not be sent cross-site, even if credentials is set to include.
访问原文 返回搜索 https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。