{"revision":"c10276e953456835cdbb1f3a60d58ae1980be353","document":{"id":764,"path":"api-reference/server-api-reference/Fetch.ResponseAPI.md","title":"Fetch Response - Scoped,Global","bundle":null,"doc_type":null,"release":"australia","body":"\n# Fetch Response- Scoped,Global\n\nThe Fetch Response API provides methods for creating a new Response object and for handling the response body created by a Fetch Request API method.\n\nThe Fetch Response API is part of a set of Fetch APIs, which provide various actions for fetching resources from external websites. The full Fetch API collection includes:\n\n-   [Fetch - fetch\\(String resource, Object options\\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/server-api-reference/FetchAPI.md): Starts the process of fetching a resource from the network.\n-   [Fetch Headers - Scoped, Global](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/server-api-reference/Fetch.HeadersAPI.md): Retrieve and modify request and response headers.\n-   [Fetch Request - Scoped, Global](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/server-api-reference/Fetch.RequestAPI.md): Create a new request object.\n-   [Fetch RequestInit - Scoped, Global](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/server-api-reference/Fetch.RequestInitAPI.md): Set options to configure a fetch request.\n-   [Fetch Response - Scoped,Global](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/server-api-reference/Fetch.ResponseAPI.md): Create a new response object.\n\nTo 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](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/platform-administration/r_AvailableSystemProperties.md).\n\n## Response properties\n\nThe 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](https://developer.mozilla.org/en-US/docs/Web/API/Response).\n\n<table id=\"table_t5x_2qw_jdc\"><thead><tr><th>\n\nProperty name\n\n</th><th>\n\nDescription\n\n</th><th>\n\nExample\n\n</th></tr></thead><tbody><tr><td>\n\nbody\n\n</td><td>\n\nReady-only. Contains a readable stream of byte data in the response body contents.Valid values: A ReadableStream or null.\n\nData type: String\n\n</td><td>\n\n```\nconst request = new Request(\"/myEndpoint\", {\n  method: \"POST\",\n  body: \"Hello world\",\n});\n\nrequest.body; // ReadableStream\n```\n\n</td></tr><tr><td>\n\nbodyUsed\n\n</td><td>\n\nReady-only. Flag that indicates whether the body has been read yet.Accepted values:\n\n-   true: Body has been read.\n-   false: Body hasn't been read.\n\nData type: Boolean\n\n</td><td>\n\n```\nconst request = new Request(\"/myEndpoint\", {\n  method: \"POST\",\n  body: \"Hello world\",\n});\n\nrequest.bodyUsed; // false\n\nrequest.text().then((bodyAsText) => {\n  console.log(request.bodyUsed); // true\n});\n```\n\n</td></tr><tr><td>\n\nheaders\n\n</td><td>\n\nRead-only. The Headers object associated with the response.Data type: Headers object\n\n</td><td>\n\n```\nconst myRequest = new Request(\"flowers.jpg\");\nconst myHeaders = myRequest.headers; // Headers {}\n```\n\n</td></tr><tr><td>\n\nok\n\n</td><td>\n\nReady-only. Flag indicating whether the response was successful \\(status in the range 200-299\\) or not.Accepted values:\n\n-   true: The response was successful.\n-   false: The response wasn't successful.\n\nData type: Boolean\n\n</td><td>\n\n```\nconst myImage = document.querySelector(\"img\");\n\nconst myRequest = new Request(\"flowers.jpg\");\n\nfetch(myRequest).then((response) => {\n  console.log(response.ok); // returns true if the response returned successfully\n  response.blob().then((myBlob) => {\n    const objectURL = URL.createObjectURL(myBlob);\n    myImage.src = objectURL;\n  });\n});\n```\n\n</td></tr><tr><td>\n\nredirected\n\n</td><td>\n\nRead-only. Flag indicating whether the response is a result that the request was redirected.Accepted values:\n\n-   true: request was redirected.\n-   false: request wasn't redirected.\n\nData type: Boolean\n\n</td><td>\n\n```\nconst myRequest = new Request(\"flowers.jpg\");\nconst myCred = myRequest.redirect;\n```\n\n</td></tr><tr><td>\n\nstatus\n\n</td><td>\n\nRead-only. HTTP status codes of the response. For example, 200 for a success.Data type: Number\n\n</td><td>\n\n```\nconst myImage = document.querySelector(\"img\");\n\nconst myRequest = new Request(\"flowers.jpg\");\n\nfetch(myRequest)\n  .then((response) => {\n    console.log(\"response.status =\", response.status); // response.status = 200\n    return response.blob();\n  })\n  .then((myBlob) => {\n    const objectURL = URL.createObjectURL(myBlob);\n    myImage.src = objectURL;\n  });\n```\n\n</td></tr><tr><td>\n\nstatusText\n\n</td><td>\n\nRead-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\n\n</td><td>\n\n```\nconst myRequest = new Request(\"flowers.jpg\");\n\n // Log the HTTP status and status text\n    console.log(`Status: ${response.status}`);\n    console.log(`Status Text: ${response.statusText}`);\n    \n    // Check if the response is successful\n    if (response.ok) {\n      console.log(\"Request succeeded!\");\n    } else {\n      console.log(\"Request failed.\");\n    }\n  } catch (error) {\n    console.error(\"Error fetching the URL:\", error);\n  }\n}\n```\n\n</td></tr><tr><td>\n\ntype\n\n</td><td>\n\nRead-only. Type of response.Accepted values:\n\n-   basic: Normal, same origin response, with all headers exposed except \"Set-Cookie\".\n-   cors: Response was received from a valid cross-origin request. Certain headers and the body may be accessed.\n-   error: Network error. No useful information describing the error is available. The Response's status is 0, headers are empty and immutable. This is the type for a Response obtained from `Response.error()`.\n-   opaque: Response for \"no-cors\" request to cross-origin resource. Severely restricted.\n-   opaqueredirect: The fetch request was made with `redirect: \"manual\"`. The Response's status is 0, headers are empty, body is null and trailer is empty.\n\nData type: String\n\n</td><td>\n\n```\nconst myImage = document.querySelector(\"img\");\n\nconst myRequest = new Request(\"flowers.jpg\");\n\nfetch(myRequest)\n  .then((response) => {\n    console.log(\"response.type =\", response.type); // response.type = 'basic'\n    return response.blob();\n  })\n  .then((myBlob) => {\n    const objectURL = URL.createObjectURL(myBlob);\n    myImage.src = objectURL;\n  });\n```\n\n</td></tr><tr><td>\n\nurl\n\n</td><td>\n\nRead-only. URL of the response.Data type: String\n\n</td><td>\n\n```\nconst myRequest = new Request(\"flowers.jpg\");\nconst myURL = myRequest.url; // \"https://github.com/mdn/dom-examples/tree/main/fetch/fetch-request/flowers.jpg\"\n```\n\n</td></tr></tbody>\n</table>**Parent Topic:**[Server API reference](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/server-api-reference/api-server.md)\n\n## Fetch Response - Response\\(Object body, Object options\\)\n\nCreates a new Response object using the Response\\(\\) constructor.\n\n<table id=\"table_bt1_vly_12c\" class=\"parameters\"><thead><tr><th>\n\nName\n\n</th><th>\n\nType\n\n</th><th>\n\nDescription\n\n</th></tr></thead><tbody><tr><td>\n\nbody\n\n</td><td>\n\nObject\n\n</td><td>\n\nOptional. An object defining a body for the response.Valid types:\n\n-   ArrayBuffer\n-   Blob\n-   DataView\n-   FormData\n-   ReadableStream\n-   String\n-   String literal\n-   TypedArray\n-   URLSearchParams\n\nDefault: null\n\n</td></tr><tr><td>\n\noptions\n\n</td><td>\n\nObject\n\n</td><td>\n\nOptional. 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:-   headers: Any headers you want to add to your response, contained within a [Fetch Headers - Scoped, Global](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/server-api-reference/Fetch.HeadersAPI.md) object or object literal of string key/value pairs \\(see [HTTP headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) for a reference\\). Empty by default.\n-   status: The status code for the response. The default value is `200`.\n-   statusText: The status message associated with the status code, such as `\"OK\"`. The default value is `\"\"`.\n\n</td></tr></tbody>\n</table>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:\n\n```\nconst myBlob = new Blob();\nconst myOptions = { status: 200, statusText: \"Status message!\" };\nconst myResponse = new Response(myBlob, myOptions);\n```\n\n## Fetch Response - arrayBuffer\\(\\)\n\nReturns a promise that resolves with an ArrayBuffer.\n\nThe arrayBuffer\\(\\) method is useful when working with binary data like images, audio files, or any other binary file that needs to be processed.\n\n|Name|Type|Description|\n|----|----|-----------|\n|None| | |\n\n|Type|Description|\n|----|-----------|\n|Object|A promise that resolves with an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), which represents a generic raw binary data buffer.|\n\n<table id=\"table_szf_1gs_kdc\" class=\"returns\"><thead><tr><th>\n\nException\n\n</th><th>\n\nDescription\n\n</th></tr></thead><tbody><tr><td>\n\nDOMException - AbortError\n\n</td><td>\n\nAn exception stating that the request was aborted.\n\n</td></tr><tr><td>\n\nTypeError\n\n</td><td>\n\nThrown for one of the following reasons: -   The response body is disturbed or locked.\n-   There was an error decoding the body content \\(for example, because the Content-Encoding header is incorrect\\).\n\n</td></tr><tr><td>\n\nRangeError\n\n</td><td>\n\nThere was a problem creating the associated `ArrayBuffer`. For example, if the data size is too large.\n\n</td></tr></tbody>\n</table>The following example script fetches binary data from a server and processes it while utilizing the arrayBuffer\\(\\) method using these steps:\n\n1.  fetch\\(\\): Fetches a resource from the specified URL.\n2.  **response.ok**: Checks if the response status is in the 200-299 range.\n3.  arrayBuffer\\(\\): Reads the response body and converts it into an ArrayBuffer, which represents a generic, fixed-length raw binary data buffer.\n4.  Uint8Array: Converts the ArrayBuffer into a Uint8Array, which is a typed array for easy manipulation of binary data.\n\n```\njavascriptCopy code// Simple API to fetch binary data and process it using arrayBuffer()asyncfunctionfetchBinaryData(url) {\n  try {\n    // Fetch the resource from the provided URLconst response = awaitfetch(url);\n\n    // Check if the response is successfulif (!response.ok) {\n      thrownewError(`HTTP error! Status: ${response.status}`);\n    }\n\n    // Convert the response body to an ArrayBufferconst arrayBuffer = await response.arrayBuffer();\n\n    // Process the ArrayBuffer (e.g., convert it to a typed array)const uint8Array = newUint8Array(arrayBuffer);\n\n    // Return the processed datareturn uint8Array;\n  } catch (error) {\n    console.error(\"Error fetching or processing binary data:\", error);\n    throw error;\n  }\n}\n\n// Example usageconst binaryDataUrl = 'https://example.com/path/to/binary/data';\n\nfetchBinaryData(binaryDataUrl)\n  .then((data) => {\n    console.log(\"Binary data as Uint8Array:\", data);\n    // Further processing can be done here, e.g., rendering an image or playing audio\n  })\n  .catch((error) => {\n    console.error(\"Failed to fetch binary data:\", error);\n  });\n```\n\n## Fetch Response - blob\\(\\)\n\nReturns a promise that resolves with a Blob.\n\n|Name|Type|Description|\n|----|----|-----------|\n|None| | |\n\n|Type|Description|\n|----|-----------|\n|Object|A promise that resolves with a [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob).|\n\n<table id=\"table_szf_1gs_kdc\" class=\"returns\"><thead><tr><th>\n\nException\n\n</th><th>\n\nDescription\n\n</th></tr></thead><tbody><tr><td>\n\nDOMException - AbortError\n\n</td><td>\n\nAn exception stating that the request was aborted.\n\n</td></tr><tr><td>\n\nTypeError\n\n</td><td>\n\nThrown for one of the following reasons: -   The response body is disturbed or locked.\n-   There was an error decoding the body content \\(for example, because the Content-Encoding header is incorrect\\).\n\n</td></tr></tbody>\n</table>The following example demonstrates how to use the blob\\(\\) method with the Fetch API using the following steps. This use case is great for fetching images or other binary content \\(like videos or PDFs\\) and displaying them dynamically.\n\n1.  fetch\\(url\\): Fetches a resource from the specified URL.\n2.  response.blob\\(\\): Converts the response body into a Blob object, which represents binary data.\n3.  URL.createObjectURL\\(blob\\): Generates a temporary URL for the Blob, which can be used in the DOM \\(for example, as an image source\\).\n4.  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.\n\n```\n\nasync function fetchBlob(url) {\n  try {\n    // Fetch the resource from the provided URL\n    const response = await fetch(url);\n\n    // Check if the response is successful\n    if (!response.ok) {\n      throw new Error(`HTTP error! Status: ${response.status}`);\n    }\n\n    // Convert the response body to a Blob\n    const blob = await response.blob();\n\n    // Create a URL for the Blob and log it\n    const blobUrl = URL.createObjectURL(blob);\n    console.log(\"Blob URL:\", blobUrl);\n\n    // For example, you can set it as the source of an image\n    const img = document.createElement('img');\n    img.src = blobUrl;\n    img.alt = \"Fetched Blob Image\";\n    document.body.appendChild(img);\n  } catch (error) {\n    console.error(\"Error fetching or processing blob:\", error);\n  }\n}\n\n// Example usage with an image URL\nconst imageUrl = 'https://via.placeholder.com/150';\nfetchBlob(imageUrl);\n```\n\n## Fetch Response - bytes\\(\\)\n\nReturns a promise that resolves with an Uint8Array.\n\n|Name|Type|Description|\n|----|----|-----------|\n|None| | |\n\n|Type|Description|\n|----|-----------|\n|Object|A promise that resolves with an Uint8Array.|\n\n<table id=\"table_szf_1gs_kdc\" class=\"returns\"><thead><tr><th>\n\nException\n\n</th><th>\n\nDescription\n\n</th></tr></thead><tbody><tr><td>\n\nDOMException- AbortError\n\n</td><td>\n\nThe request was aborted.\n\n</td></tr><tr><td>\n\nTypeError\n\n</td><td>\n\nThrown for one of the following reasons: -   The response body is disturbed or locked.\n-   There was an error decoding the body content \\(for example, because the Content-Encoding header is incorrect\\).\n\n</td></tr><tr><td>\n\nRangeError\n\n</td><td>\n\nThere was a problem creating the associated `ArrayBuffer`. For example, if the data size is too large.\n\n</td></tr></tbody>\n</table>The following example shows how to fetch a text file, return the body as a Uint8Array, and then decode this into a string.\n\n```\nconst response = await fetch(\"https://www.example.com/textfile.txt\");\nconst textFile = await response.bytes();\nconst string = new TextDecoder().decode(textFile);\nconsole.log(string);\n```\n\n## Fetch Response - formData\\(\\)\n\nReturns a promise that resolves with a FormData object.\n\n|Name|Type|Description|\n|----|----|-----------|\n|None| | |\n\n|Type|Description|\n|----|-----------|\n|Object|A promise that resolves with a [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) object.|\n\n<table id=\"table_szf_1gs_kdc\" class=\"returns\"><thead><tr><th>\n\nException\n\n</th><th>\n\nDescription\n\n</th></tr></thead><tbody><tr><td>\n\nDOMException- AbortError\n\n</td><td>\n\nThe request was aborted.\n\n</td></tr><tr><td>\n\nTypeError\n\n</td><td>\n\nThrown for one of the following reasons: -   The response body is disturbed or locked.\n-   There was an error decoding the body content \\(for example, because the Content-Encoding header is incorrect\\).\n\n</td></tr></tbody>\n</table>The following example demonstrates how to use formData\\(\\) to process a form submission response using the following steps:\n\n1.  Request Body: Used `JSON.stringify()` to send the form data as JSON instead of URL-encoded parameters.\n2.  Content-Type: Set to `application/json` to indicate the request body format.\n\n```\n// Example of using Response.formData()\nasync function fetchFormData(url) {\n  try {\n    // Make a POST request to fetch the form data\n    const response = await fetch(url, {\n      method: 'POST',\n      body: JSON.stringify({\n        name: 'John Doe',\n        email: 'john.doe@example.com',\n      }),\n      headers: {\n        'Content-Type': 'application/json',\n      },\n    });\n\n    // Check if the response is successful\n    if (!response.ok) {\n      throw new Error(`HTTP error! Status: ${response.status}`);\n    }\n\n    // Parse the response as FormData\n    const formData = await response.formData();\n\n    // Iterate through the FormData entries\n    for (const [key, value] of formData.entries()) {\n      console.log(`${key}: ${value}`);\n    }\n  } catch (error) {\n    console.error(\"Error fetching or processing form data:\", error);\n  }\n}\n\n// Example usage\nconst formEndpoint = 'https://httpbin.org/post'; // Replace with your form endpoint\nfetchFormData(formEndpoint);\n```\n\nOutput:\n\n```\nname: John Doe\nemail: john.doe@example.com\n```\n\n## Fetch Response - json\\(\\)\n\nReturns a promise that resolves to the result of parsing the body text as JSON.\n\n**Note:** Despite the name of this method, the result of json\\(\\) is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object.\n\n|Name|Type|Description|\n|----|----|-----------|\n|None| | |\n\n|Type|Description|\n|----|-----------|\n|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.|\n\n<table id=\"table_szf_1gs_kdc\" class=\"returns\"><thead><tr><th>\n\nException\n\n</th><th>\n\nDescription\n\n</th></tr></thead><tbody><tr><td>\n\nDOMException- AbortError\n\n</td><td>\n\nThe request was aborted.\n\n</td></tr><tr><td>\n\nTypeError\n\n</td><td>\n\nThrown for one of the following reasons: -   The response body is disturbed or locked.\n-   There was an error decoding the body content \\(for example, because the Content-Encoding header is incorrect\\).\n\n</td></tr><tr><td>\n\nSyntaxError\n\n</td><td>\n\nThe response body cannot be parsed as JSON.\n\n</td></tr></tbody>\n</table>The following example demonstrates how to use json\\(\\) to form a response:\n\n1.  fetch\\(\\) makes a GET request to the URL.\n2.  The **response.ok** checks if the request was successful \\(status code 200–299\\).\n3.  If successful, response.json\\(\\) is called to parse the JSON data from the response.\n4.  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.\n\n```\nfetch('https://jsonplaceholder.typicode.com/posts/1')\n  .then(response => {\n    if (!response.ok) {\n      throw new Error('Network response was not ok');\n    }\n    return response.json();\n  })\n  .then(data => console.log(data))\n  .catch(error => console.error('Fetch error:', error));\n```\n\n## Fetch Response - text\\(\\)\n\nReads the response body and returns it as a plain string. The response is always decoded using UTF-8.\n\nThe 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.\n\n|Name|Type|Description|\n|----|----|-----------|\n|None| | |\n\n|Type|Description|\n|----|-----------|\n|None|A promise that resolves with a UTF-8-enconded string.|\n\n<table id=\"table_szf_1gs_kdc\" class=\"returns\"><thead><tr><th>\n\nException\n\n</th><th>\n\nDescription\n\n</th></tr></thead><tbody><tr><td>\n\nDOMException- AbortError\n\n</td><td>\n\nThe request was aborted.\n\n</td></tr><tr><td>\n\nTypeError\n\n</td><td>\n\nThrown for one of the following reasons: -   The response body is disturbed or locked.\n-   There was an error decoding the body content \\(for example, because the Content-Encoding header is incorrect\\).\n\n</td></tr></tbody>\n</table>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`.\n\n```\nconst response = awaitfetch('https://example.com/text-endpoint');\nconst text = await response.text();\nconsole.log(text); // Outputs: Hello, world! This is a sample response.\n```\n\nOutput:\n\n```\nHello, world! This is a sample response.\n```\n\n"}}