You can call the Fetch API operation to retrieve data from points of presence (POPs) over HTTP or HTTPS and return the data to users. It functions similarly to the Fetch API in browser environments and can be used for scenarios such as dynamic loading of content, interaction with backend services, and A/B testing.
Fetch API methods
Fetch supports asynchronous calls. Fetch does not block script execution as long as you do not use the await keyword. Fetch allows you to send up to four subrequests at a time. The underlying layer uses persistent connections, ensuring stable performance without requiring you to manage connection pools.
You can call the Fetch API to send HTTP or HTTPS requests. Each redirect is considered one request. Each Fetch API request supports up to 12 redirect operations.
Method definition
fetch(arg, init)is used as the Fetch method. For more information, see WorkerOrGlobalScope.fetch().Method limits
The Fetch API supports domain names but does not support IP addresses. HTTP requests use port 80 and HTTPS requests use port 443.
The
initparameter's internalcredentials,referrer,referrerPolicy,cacheandintegrityparameters are not in use.By default, the
redirectparameter is set tofollow, which specifies that fetch requests follow 3xx redirects. If you don't want fetch requests to follow 3xx redirects, set theredirectparameter tomanual.
NoteBrowsers process fetch requests the same way across different modes. For example, you can use
CROS fetchto retrieve resources from any origin servers by using Alibaba Cloud CDN, DCDN, or ESA.To send more than four subrequests at a time, submit a ticket to request a quota increase.
The total length of a request URL cannot exceed 4 KB.
If you use Fetch to obtain resources that are compressed in Gzip, these resources are automatically decompressed before they are returned. If you do not want the resources to be decompressed by default, you can set the decompress parameter to
manualas described in the Decompress section.
Configure a timeout period
Timeout/** * Deploy request timeout * * @param {Number} timeout. Timeout period. Unit: ms. * @param {Object} config. Timeout configuration. * - @param {Object|Funtion} handler. Return value if the operation times out. * @returns */ const RequestTimeout = (timeout, config) => { return new Promise((resolve) => { const { handler = null } = config; let timer = setTimeout(() => { clearTimeout(timer); timer = null; const defaultRes = (typeof handler === 'function' ? handler() : handler) || {}; resolve(defaultRes); }, timeout); }); };Sample request
const KV_TIMEOUT = 1000; let edgekv = new EdgeKV({ namespace: KV_NS, }); let kvRequest = edgekv.get(key, getType); let timeoutPromise = RequestTimeout(KV_TIMEOUT, { handler: { res: {}, errorMessage: `kv request timeout (${KV_TIMEOUT}ms)`, } }); let resp = await Promise.race([ kvRequest, timeoutPromise, ]); if (resp === undefined) { return "kv not found, key = " + key; } else { return resp; }
Redirect
The Fetch API supports 3xx redirects. HTTP 3xx status codes include 301, 302, 303, 307, and 308. You can set the redirect parameter to one of the following values:
{redirect: "manual"}: does not follow 3xx redirects. You need to handle the redirects yourself.{redirect: "error"}: throws an error when a 3xx status code is returned.{redirect: "follow"}: (default) follows 3xx redirects. Up to 20 redirects are supported.
The following table describes 3xx redirects.
Status code | Description |
301, 302, 303, and 308 | The request method is changed to GET, and the body is ignored. |
307 | Fetch requests follow the redirect only if the request method is GET. If the request method is not GET, an exception is thrown. |
The URL to which a request is redirected is contained in the Location header. If the Location header is missing, an exception is thrown.
The Location header can contain a list of URLs that are separated by commas (,). Requests are redirected only to the first URL in the list. Other URLs are ignored.
The Location header can contain absolute URLs or relative URLs.
Decompress
The Fetch API allows you to configure a decompression mode, such as fetch("https://www.example.com",{decompress: "manual"}). The decompress parameter supports the following values:
manual: does not decompress data. If the server returns compressed data upon a fetch request, the data received by EdgeRoutine (ER) is also compressed.
decompress: automatically decompresses data. This is the default value. The Fetch API supports Gzip compression. ER automatically detects or decompresses data based on the Content-Encoding header. After ER decompresses data, ER changes the value of Content-Encoding. If the Gzip parameter is deleted, you can configure the following settings to prevent exceptions during data transmission:
content-encoding: gzip: ER recognizes the value of Content-Encoding and decompresses data.content-encoding: gzip, identity: ER recognizes the value of Content-Encoding and decompresses data.
NoteAlgorithms other than Gzip cause exceptions.
fallbackIdentity: The effect of this value is similar to the effect of the value decompress. If ER cannot recognize this value, ER does not decompress data.
After the Fetch API automatically decompresses data, you cannot pass the Content-Length header as needed if the response contains the Content-Length header. This is because the Content-Length header indicates the size of the data before decompression.
content-length
If you configure the Content-Length header in a fetch request, data is encoded in the format that is specified in the Content-Length header, and the method used by the Fetch API to transmit data is changed. If you do not configure the Content-Length header, the Fetch API automatically fetches all data in the body stream and transmits the data. The transmitted data is encoded by using the chunked transfer encoding scheme.
Content-LengthsettingsIf the
Content-Lengthheader is set to a non-negative value, the Fetch API fetches data from the body stream based on theContent-Lengthheader and transmits the fetched data. IfContent-Lengthis set to 0, no data is transmitted.If the
Content-Lengthheader is set to an invalid value, the Fetch API transmits all values in the body. The transmitted data is encoded by using the chunked transfer encoding scheme.
Examples
The Fetch API automatically decompresses data. After the data is decompressed, the
Content-Lengthheader is retained in the response. TheContent-Lengthheader indicates the size of data before the data is decompressed. If you call the Fetch API after you modify the body, check whether theContent-Lengthheader needs to be modified.In the following example, a POST request that contains the
Content-Lengthheader is sent from a client. When you call the Fetch API to retrieve data, the request body uses the Headers object from the client request. The value of theContent-Lengthheader may be different from the actual size of the body. If the Headers object is transmitted, check whether the size of the body is changed.export default { fetch(request) { return handleRequest(request) } } async function handleRequest(request) { return fetch("http://www.example.com", { headers: request.headers, method: request.method, body: "SomeData" }); }
Headers
Definition
For more information about the Headers object, see Headers.
Limits
A header records the amount of memory resources that are consumed. The maximum size of a Headers object is 8 KB. If the size of a Headers object exceeds this limit, a JavaScript exception is thrown.
Blacklist
The Fetch API uses a header blacklist. If you attempt to read or write a header that is in the blacklist, an exception is thrown. The following table describes the headers that are included in the blacklist.
expect
te
trailer
upgrade
proxy-connection
connection
keep-alive
dnt
host
Reserved headers
Request
Description
For more information about the Request operation, see Request.
Limits
The following properties of the Request object are not in use in the CDN/DCDN/ESA context.
context
credentials
destination
integrity
mode
referrer
referrerPolicy
cache
Use cases
Fetches the request method:
request.method.Fetches the request URL:
request.url.Fetches the request header:
request.headers.Fetches the request payload:
request.body. The body is a ReadableStream object.Fetches JSON data:
await request.json().Fetches form data:
await request.formData().Fetches strings encoded in UTF-8:
await request.text().
The Request operation is a standard API operation. The Request operation ignores the body when it fetches all values of the body without the need to consume the memory resources of ER. This minimizes the garbage collection (GC) pause time and ensures that all values of the request body are fetched from the underlying sockets. For
await request.ignore(), if you do not need to read the fetched body or are not interested in it, we recommend that you callrequest.ignorefor all fetch requests to improve performance. This is because the runtime automatically sends requests with fully read bodies to the connection pool for future use.
Response
Description
For more information about the Response operation, see Response.
Limits
The useFinalURLS and error properties of the Response object are not implemented and have no meaning in the CDN/DCDN/ESA context.
Use cases
Fetches the response code:
response.status.Fetches the reason phrase of a response:
response.statusText.Fetches the response header:
response.headers.Fetches the response URL:
response.url, which indicates the URL to which the response was sent.Fetches a list of all redirect URLs (non-standard):
response.urlList. Similar to how the Request object implements the body mixin, you can use similar methods to obtain the body object.
FormData
Definition
For more information about the FormData operation, see FormData.
Limits
The FormData operation is similar to the Headers operation. FormData limits the size of headers. If the size of a header exceeds the upper limit, an exception is thrown. If you send FormData as an HTTP request body,
content-typeis set toform-data/multipartby default.
URLSearchParams
Definition
For more information about the URLSearchParams operation, see URLSearchParams().
Limits
If you send URLSearchParams as an HTTP request body,
content-typeis set toapplication/x-www-form-urlencodeby default. The data size cannot exceed 1,000 bytes.
Blob and File
Definition
Limits
ER supports the Blob and File classes, which meet the standards of the Blob and File operations. ER cannot read or write files. You can pass the Blob and File classes supported by ER to the response body. The value of the
content-typeheader is the same as the MIME type in theBloborFileoperation.