Fetch Response - Scoped,Global
The Fetch Response API provides methods for creating a new Response object and for handling the response body created by a Fetch Request API method.
- Fetch - fetch(String resource, Object options): Starts the process of fetching a resource from the network.
- Fetch Headers - Scoped, Global: Retrieve and modify request and response headers.
- Fetch Request - Scoped, Global: Create a new request object.
- Fetch RequestInit - Scoped, Global: Set options to configure a fetch request.
- Fetch Response - Scoped,Global: Create a new response object.
To support fetch actions, the system property, glide.hosts.allowlist, allows controls over what hosts a fetch method can access. It applies to HTTP APIs like RestMessageV2 and those mentioned
above. For more information about glide.hosts.allowlist, see Available system properties.
Response properties
The Response API provides properties that return details about the HTTP response. These properties allow you to access metadata (like status, headers, type) and
the response body (body) for further processing. They enable checking the success of a request (ok) and parsing the returned data in various formats (for example, JSON or text). These properties are
important for validating and handling server responses in client-side applications. To read more in-depth explanations about each property, see https://developer.mozilla.org/en-US/docs/Web/API/Response.
| Property name | Description | Example |
|---|---|---|
| body | Ready-only. Contains a readable stream of byte data in the response body contents. Valid values: A ReadableStream or null. Data type: String |
|
| bodyUsed | Ready-only. Flag that indicates whether the body has been read yet. Accepted values:
Data type: Boolean |
|
| headers | Read-only. The Headers object associated with the response. Data type: Headers object |
|
| ok | Ready-only. Flag indicating whether the response was successful (status in the range 200-299) or not. Accepted values:
Data type: Boolean |
|
| redirected | Read-only. Flag indicating whether the response is a result that the request was redirected. Accepted values:
Data type: Boolean |
|
| status | Read-only. HTTP status codes of the response. For example, 200 for a success. Data type: Number |
|
| statusText | Read-only. Status message corresponding to the HTTP status code in response.status. For example, this would be OK for a status code 200, Continue for
100, Not Found for 404.Data type: String |
|
| type | Read-only. Type of response. Accepted values:
Data type: String |
|
| url | Read-only. URL of the response. Data type: String |
|
Fetch Response - Response(Object body, Object options)
Creates a new Response object using the Response() constructor.
| Name | Type | Description |
|---|---|---|
| body | Object | Optional. An object defining a body for the response. Valid types:
Default: null |
| options | Object | Optional. An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are:
|
In this example, we create a new Response object using the constructor, passing a new Blob as a body, and an init object containing custom status and statusText options:
const myBlob = new Blob();
const myOptions = { status: 200, statusText: "Status message!" };
const myResponse = new Response(myBlob, myOptions);
Fetch Response - arrayBuffer()
Returns a promise that resolves with an ArrayBuffer.
The arrayBuffer() method is useful when working with binary data like images, audio files, or any other binary file that needs to be processed.
| Name | Type | Description |
|---|---|---|
| None |
| Type | Description |
|---|---|
| Object | A promise that resolves with an ArrayBuffer, which represents a generic raw binary data buffer. |
| Exception | Description |
|---|---|
| DOMException - AbortError | An exception stating that the request was aborted. |
| TypeError | Thrown for one of the following reasons:
|
| RangeError | There was a problem creating the associated ArrayBuffer. For example, if the data size is too large. |
- fetch(): Fetches a resource from the specified URL.
- response.ok: Checks if the response status is in the 200-299 range.
- arrayBuffer(): Reads the response body and converts it into an ArrayBuffer, which represents a generic, fixed-length raw binary data buffer.
- Uint8Array: Converts the ArrayBuffer into a Uint8Array, which is a typed array for easy manipulation of binary data.
javascriptCopy code// Simple API to fetch binary data and process it using arrayBuffer()asyncfunctionfetchBinaryData(url) {
try {
// Fetch the resource from the provided URLconst response = awaitfetch(url);
// Check if the response is successfulif (!response.ok) {
thrownewError(`HTTP error! Status: ${response.status}`);
}
// Convert the response body to an ArrayBufferconst arrayBuffer = await response.arrayBuffer();
// Process the ArrayBuffer (e.g., convert it to a typed array)const uint8Array = newUint8Array(arrayBuffer);
// Return the processed datareturn uint8Array;
} catch (error) {
console.error("Error fetching or processing binary data:", error);
throw error;
}
}
// Example usageconst binaryDataUrl = 'https://example.com/path/to/binary/data';
fetchBinaryData(binaryDataUrl)
.then((data) => {
console.log("Binary data as Uint8Array:", data);
// Further processing can be done here, e.g., rendering an image or playing audio
})
.catch((error) => {
console.error("Failed to fetch binary data:", error);
});Fetch Response - blob()
Returns a promise that resolves with a Blob.
| Name | Type | Description |
|---|---|---|
| None |
| Type | Description |
|---|---|
| Object | A promise that resolves with a Blob. |
| Exception | Description |
|---|---|
| DOMException - AbortError | An exception stating that the request was aborted. |
| TypeError | Thrown for one of the following reasons:
|
- fetch(url): Fetches a resource from the specified URL.
- response.blob(): Converts the response body into a Blob object, which represents binary data.
- URL.createObjectURL(blob): Generates a temporary URL for the Blob, which can be used in the DOM (for example, as an image source).
- Appending the image to the DOM: Dynamically creates an image element, sets the blob URL as its source, and appends it to the document body.
async function fetchBlob(url) {
try {
// Fetch the resource from the provided URL
const response = await fetch(url);
// Check if the response is successful
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Convert the response body to a Blob
const blob = await response.blob();
// Create a URL for the Blob and log it
const blobUrl = URL.createObjectURL(blob);
console.log("Blob URL:", blobUrl);
// For example, you can set it as the source of an image
const img = document.createElement('img');
img.src = blobUrl;
img.alt = "Fetched Blob Image";
document.body.appendChild(img);
} catch (error) {
console.error("Error fetching or processing blob:", error);
}
}
// Example usage with an image URL
const imageUrl = 'https://via.placeholder.com/150';
fetchBlob(imageUrl);
Fetch Response - bytes()
Returns a promise that resolves with an Uint8Array.
| Name | Type | Description |
|---|---|---|
| None |
| Type | Description |
|---|---|
| Object | A promise that resolves with an Uint8Array. |
| Exception | Description |
|---|---|
| DOMException- AbortError | The request was aborted. |
| TypeError | Thrown for one of the following reasons:
|
| RangeError | There was a problem creating the associated ArrayBuffer. For example, if the data size is too large. |
The following example shows how to fetch a text file, return the body as a Uint8Array, and then decode this into a string.
const response = await fetch("https://www.example.com/textfile.txt");
const textFile = await response.bytes();
const string = new TextDecoder().decode(textFile);
console.log(string);
Fetch Response - formData()
Returns a promise that resolves with a FormData object.
| Name | Type | Description |
|---|---|---|
| None |
| Type | Description |
|---|---|
| Object | A promise that resolves with a FormData object. |
| Exception | Description |
|---|---|
| DOMException- AbortError | The request was aborted. |
| TypeError | Thrown for one of the following reasons:
|
- Request Body: Used
JSON.stringify()to send the form data as JSON instead of URL-encoded parameters. - Content-Type: Set to
application/jsonto indicate the request body format.
// Example of using Response.formData()
async function fetchFormData(url) {
try {
// Make a POST request to fetch the form data
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify({
name: 'John Doe',
email: 'john.doe@example.com',
}),
headers: {
'Content-Type': 'application/json',
},
});
// Check if the response is successful
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as FormData
const formData = await response.formData();
// Iterate through the FormData entries
for (const [key, value] of formData.entries()) {
console.log(`${key}: ${value}`);
}
} catch (error) {
console.error("Error fetching or processing form data:", error);
}
}
// Example usage
const formEndpoint = 'https://httpbin.org/post'; // Replace with your form endpoint
fetchFormData(formEndpoint);
Output:
name: John Doe
email: john.doe@example.com
Fetch Response - json()
Returns a promise that resolves to the result of parsing the body text as JSON.
| Name | Type | Description |
|---|---|---|
| None |
| Type | Description |
|---|---|
| Object | A promise that resolves to a JavaScript object. This object could be anything that can be represented by JSON, like an object, array, string, number, and so on. |
| Exception | Description |
|---|---|
| DOMException- AbortError | The request was aborted. |
| TypeError | Thrown for one of the following reasons:
|
| SyntaxError | The response body cannot be parsed as JSON. |
- fetch() makes a GET request to the URL.
- The response.ok checks if the request was successful (status code 200–299).
- If successful, response.json() is called to parse the JSON data from the response.
- The parsed data is logged to system logs using the Console API. If any error occurs during the request or parsing, it's caught and logged.
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
Fetch Response - text()
Reads the response body and returns it as a plain string. The response is always decoded using UTF-8.
The text() method is useful for responses that contain textual data, such as HTML, JSON (if you want to handle it manually), XML, or plain text files that are meant to be treated as plain strings.
| Name | Type | Description |
|---|---|---|
| None |
| Type | Description |
|---|---|
| None | A promise that resolves with a UTF-8-enconded string. |
| Exception | Description |
|---|---|
| DOMException- AbortError | The request was aborted. |
| TypeError | Thrown for one of the following reasons:
|
The following example shows how a simple way to use text() when the server returns plain text, like Hello, world! This is a sample response.
const response = awaitfetch('https://example.com/text-endpoint');
const text = await response.text();
console.log(text); // Outputs: Hello, world! This is a sample response.
Output:
Hello, world! This is a sample response.