Fetch API – Body Data ”; Previous Next Fetch API is modern technology to send or receive data asynchronously without refreshing a web page. It provides an interface to create HTTP requests in the web browser. It is supported by almost all modern web browsers. We can also say that, by using the Fetch API we can fetch resources like JSON data, HTML pages, etc from the web server and can send data to the server using different HTTP requests like PUT, POST, etc. So in this article, we will learn what is body data, and how we are we are going to use body data. Body Data In Fetch API, both request and response contain body data. Body data in the request is an instance which contains the data which we want to send to the server whereas body data in the response is an instance which contains the data requested by the user. It is generally used by PUT or POST requests to send data to the server. It can be an instance of ArrayBuffer, TypedArray, DataView, Blob, File, String, URLSearchParams, or FormData. While sending body data you also need to set a header in the request so that the server will know what type of the data is. The Request and Response interface provides various methods to extract the body and they are − Request. arrayBuffer() − This method is used to resolve a promise with ArrayBuffer representation of the request body. Request.blob() − This method is used to resolve a promise with a blob representation of the request body. Request.formData() − This method is used to resolve a promise with formData representation of the request body. Request.json() − This method is used to parse the request body as JSON and resolve a promise with the result of parsing. Request.text() − This method is used to resolve a promise with a text representation of the request body. Response.arrayBuffer() − This method is used to return a promise which will resolve with an ArrayBuffer representation of the response body. Response.blob() − This method is used to return a promise which will resolve with a Blob representation of the response body. Response.formData() − This method is used to return a promise which will resolve with a FormData representation of the response body. Response.json() − This method is used to parse the response body as JSON and return a promise that will resolve with the result of parsing. Response.text() − This method is used to return a promise which will resolve with a text representation of the response body. All these methods return a promise which will resolve with the actual content of the body. Body data is generally used with the fetch() function. Here it is optional you can only use the body parameter when you want to send data to the server. Syntax fetch(resourceURL,{ Method: ”POST”, body:{ Name: “Monika”, Age: 34, City: “Pune” }, headers: {”content-Type”:”application/json”} }) The parameters of the fetch() function − resourceURL − It represents the resource which we want to fetch. It can be a string, a request object, or a URL of the resource. method − It represents the request method such as GET, POST, PUT and DELETE. headers − It is used to add a header to your request. body − It is used to add data to your request. It is not used by GET or HEAD methods. In the following program, we send body data using the POST method. So we create an HTML code in which we send data using JavaScript script to the server. In the script, we define a fetch() function which sends the data present in the body parameter to the given URL using the POST request method. Here the header is set to “application/json” which indicates that we are sending data. Before sending the request to the server we convert the data into JSON string with the help of JSON.stringify() function. After receiving the response from the server, we check if the response is ok or not. If yes, then we parse the response body into JSON using the response.json() function and then display the result on the output screen. If we get any error, then the error is handled by the catch() block. Example <!DOCTYPE html> <html> <body> <script> // Retrieving data from the URL using the POST request fetch(“https://jsonplaceholder.typicode.com/todos”, { // Adding POST request method: “POST”, // Adding body which we want to send body: JSON.stringify({ id: 45, title: “Tom like finger chips”, age: 34 }), // Adding header headers:{“Content-type”: “application/json; charset=UTF-8”} }) // Converting received information into JSON .then(response =>{ if (response.ok){ return response.json() } }) .then(myData => { // Display the retrieve Data console.log(“Data Sent Successfully”); // Display output document.getElementById(“sendData”).innerHTML = JSON.stringify(myData); }).catch(err=>{ console.log(“Found error:”, err) }); </script> <h2>Sent Data</h2> <div> <!– Displaying retrevie data–> <p id = “sendData”></p> </div> </body> </html> Output Conclusion So, this is how we can use Body Data in Fetch API. Using the data body we can send data from the web browser to the web server or vice versa. In the request body, body data is only used with PUT and POST request methods because using this request we can send data to the server. It is not used with GET request because GET request is used to fetch data from the server. Now in the next article, we will learn Credentials in Fetch API. Print Page Previous Next Advertisements ”;
Category: ajax
Fetch API – Handling Binary Data ”; Previous Next Binary data is data that is in the binary format not in the text format e.g. new Uint8Array([0x43, 0x21]). It includes images, audio, videos, and other files that are not in plain text. We can send and receive binary data in the Fetch API. While working with binary data in Fetch API it is important to set proper headers and response types. For binary data, we use “Content-Type”: “application/octet-stream” and the “responseType” property to “arraybuffer” or “blob” which indicates that binary data is received. Let us understand how to Send and Receive Binary Data in Fetch API using the following examples. Sending Binary Data To send binary data we use send() method of XMLHttpRequest which can easily transmit binary data using ArrayBuffer, Blob or File object. Example In the following program, we create a program which will send binary data to the server. So first we create binary data, and then we convert the binary data into Blob using Blob() constructor. Here this constructor takes two arguments: binary data and headers for the binary data. Then we create a FormData object and add Blob to the FormData object. Then we use the fetch() function to send the request to the server and then handle the response returned by the server and handle the error if occurs. <!DOCTYPE html> <html> <body> <script> // Binary data var BinaryData = new Uint8Array([0x32, 0x21, 0x45, 0x67]); // Converting binary data into Blob var blobObj = new Blob([BinaryData], {type: ”application/octet-stream”}); // Creating FormData object var obj = new FormData(); // Add data to the object // Here myfile is the name of the form field obj.append(“myfile”, blobObj); // Sending data using POST request fetch(“https://jsonplaceholder.typicode.com/todos”, { // Adding POST request method: “POST”, // Adding body which we want to send body: obj }) // Handling the response .then(response =>{ if (response.ok){ console.log(“Binary data send Successfully”); } }) // Handling the error .catch(err=>{ console.log(“Found error:”, err) }); </script> <h2>Sent Binary Data</h2> </body> </html> Output Receiving Binary Data In Fetch API, receiving binary data means retrieving the response data from the server after making the request. To receive binary data we have set the correct value of the responseType either ArrayBuffer(), or Blob(). Example In the following program, we create a program which will receive binary data from the server. So we use the fetch() function to get binary data from the given URL. In the fetch() we define headers which tell the browser we are expecting a binary response and set responseType to arraybuffer so that it tells the browser that you are receiving a response as an ArrayBuffer. Then we receive the promise in the.then() block and check the status is OK. If the status is OK, then convert the response to ArrayBuffer with the help of the arrayBuffer() function. The next .then() processes the return binary data and displays the data accordingly. The .catch() function handles the error if occurs. <!DOCTYPE html> <html> <body> <script> // Receiving data using GET request fetch(“https://jsonplaceholder.typicode.com/todos”, { // Adding Get request method: “GET”, // Setting headers headers: { ”Content-Type”: ”application/octet-stream”, }, // Setting response type to arraybuffer responseType: “arraybuffer” }) // Handling the received binary data .then(response =>{ if (response.ok){ return response.arrayBuffer(); } console.log(“Binary data send Successfully”); }) .then(arraybuffer => console.log(“Binary data received Successfully”)) // Handling the error .catch(err=>{ console.log(“Found error:”, err) }); </script> <h2>Binary Data Example</h2> </body> </html> Output Conclusion So this is how we can handle binary data using Fetch API. To handle binary data we need to convert binary data to an appropriate data format. We can also send binary data in the file, string, ArrayBuffer, and Blob. Now in the next chapter, we will learn how to find status codes using Fetch API. Print Page Previous Next Advertisements ”;
Fetch API – Response
Fetch API – Response ”; Previous Next Fetch API provides a special interface to create a response to a request and the name of that interface is Response. This interface provides a Response() constructor to create a response object. It provides various methods and properties to access and handle response data. Constructor To create a response object we can use the Response() constructor along with a new keyword. This constructor may or may not contain parameters. Syntax const newResponse = New Response() Or const newResponse = New Response(rBody) Or const newResponse = New Response(rBody, rOption) The Response() constructor has the following parameters − rBody − It represents an object which defines a body for the response. Its value can be null(default value) or blob, ArrayBuffer, TypedArray, DataView, FormData, String, URLSearchParams, a string literal, or ReadableStream. Options − It is an object which is used to provide customised settings which we want to apply to the response and the options are: headers − It is used to add a header to your response. By default the value of this parameter is empty. Its value can be a Header object or an object literal of string. status − This parameter represents the status code for the response. Its default value is 200. statusText − This parameter represent a status message related to the status code like “Not Found”. Its default value is “”. Example In the following program, we fetch the data from the given URL using the fetch() function and then display the response data in JSON format. <!DOCTYPE html> <html> <body> <script> // Data const option = {message: “Hello Tom. How are you?”}; // creating header object const newResponse = new Response(JSON.stringify(option), { status: 200, statusText:” Receive data successfully” }); // Displaying response console.log(newResponse) </script> <h2>Fetch API Example</h2> <div> <!– Displaying retrieved data–> <p id=”sendData”></p> </div> </body> </html> Output Instance Properties The properties provided by the Response interface are the read-only properties. So the commonly used properties are − Sr.No. Property & Description 1 Response.body This property contains a ReadableStream body content. 2 Response.ok This property checks whether the response was successful or not. The value of this property is in boolean. 3 Response.bodyUsed This property is used to check whether the body is used in the response or not. Its value is boolean. 4 Response.redirected This property is used to check whether the response is the result of the redirect or not. Its value is in boolean. 5 Response.status This property contains the status code of the response. 6 Response.statusText This property provides the status message according to the status code. 7 Response.type This property provides the type of response. 8 Response.url This peoperty provides the url of the response. 9 Response.header This property provides the Header object of the given response. Example In the following program, we use the properties provided by the Response interface. <!DOCTYPE html> <html> <body> <h2>Fetch API Example</h2> <script> // GET request using fetch()function fetch(“https://jsonplaceholder.typicode.com/todos”) .then(response => { // Finding response URL console.log(“URL is: “, response.url); // Getting response text console.log(“Status Text: “, response.statusText); // Getting response status console.log(“Status Code: “, response.status); }).catch(err =>{ // Handling error console.log(“Found Error:”, err); }); </script> </body> </html> Output Methods The following are the commonly used method of Response interface − Sr.No. Method & Description 1 Request.arrayBuffer() This method is used to return a promise which will resolve with the ArrayBuffer representation of the response body. 2 Request.blob() This method is used to return a promise which will resolve with Blob representation of the response body. 3 Request.clone() This method is used to create a copy of the current response object. 4 Request.json() This method is used to parse the response body as JSON and return a promise that will resolve with the result of parsing. 5 Request.text() This method is used to return a promise which will resolve with a text representation of the response body. 6 Request.formData() This method is used to return a promise which will resolve with a FormData representation of the response body. 7 Response.error() This method returns a new Response object related to a network error. It is a static method. 8 Response.redirect This method returns a new Response object with a different URL. It is a static method. 9 Response.json() This method returns a new Response object for the returning JSON encoded data. It is a static method. Example In the following program, we use the methods provided by the Response interface. So here we are going to use the json() function to parse the response in the JSON format. <!DOCTYPE html> <html> <body> <script> // GET request using fetch()function fetch(“https://jsonplaceholder.typicode.com/todos/2”, { // Method Type method: “GET”}) // Parsing the response data into JSON // Using json() function .then(response => response.json()) .then(myData => { // Display output document.getElementById(“manager”).innerHTML = JSON.stringify(myData); }).catch(newError =>{ // Handling error console.log(“Found Error:”, newError) }); </script> <h2>Display Data</h2> <div> <!– Displaying retrevie data–> <table id = “manager”></table> </div> </body> </html> Output Conclusion So this is how the Response interface works with fetch API. Using the Response interface we can extract and process the response provided by the server. It also provides various methods and properties for extracting and processing the response. Now in the
Fetch API – Custom Request Object ”; Previous Next In Fetch API, we can also create a custom Request object with the help Request() constructor of the Request interface. The Request interface provides us with more control and flexibility over the HTTP request. It provides various options like URL, method, body, headers, etc. which help us to create the customized HTTP request. Before creating a custom request object we first understand the Request() constructor using which we can able to create a Request object. Request() Constructor To create a request object we can use Request() constructor along with a new keyword. This constructor contains one mandatory parameter which is the URL of the resource and the other parameter is optional. Syntax const newRequest = New Request(resourceURL) Or const newRequest = New Request(resourceURL, optional) The Request() constructor has the following parameters − resourceURL − It represents the resource which we want to fetch. It can be a URL of the resource or the Request object. Options − It is an object which is used to provide customized settings which we want to apply on the request and the options are − method − It represents the request method such as GET, POST, PUT and DELETE. headers − It is used to add a header to your request. body − It is used to add data to your request. It is not used by GET or HEAD methods. mode − It represents the mode which you want to use for the request. The value of this parameter can be cors, same-origin, no-cors or navigate. By default the value of the mode parameter is cors. credentials − It represents the credentials which you want to use for the request. The default value of this parameter is same-origin but you can also use values like omit, same-origin, or include according to your need. cache − It represents the cache mode you want for your request. redirect − It is used for redirect mode. The value of this parameter can be: follow, error, or manual. By default is parameter is set for follow value. referrer − It represents a string which specifies the referrer of the request. The possible values of this parameter are client, URL, or no-referrer. The default value of this parameter is about the client. referrerPolicy − It is used to specify the referrer policy. integrity − It is used to represent the subresource integrity value of the given request. keepalive − It contains a boolean value to determine whether to create a persistent connection for the multiple requests/response or not. signal − It contains an AbortSignal object which is used to communicate with or abort a request. priority − It is used to specify the priority of the request as compared to other requests. This parameter can have any one of the following values − high − If we want to set the priority of the current fetch request to high as compared to others. low − If we want to set the priority of the current fetch request to low as compared to others. auto − To automatically find the priority of the current fetch request as compared to others. Custom Request object To create a custom request object we need to follow the following steps − Step 1 − Customize the Request option optional ={ method: “POST”, headers: {“Content-Type”: “application/json”}, body = { Name: “Tom”, Age: 23} }; Step 2 − Create a custom request object using the Request() constructor. const newRequest = new Request(resourceURL, optional Step 3 − Fetch the request object using the fetch() function. fetch(newRequest) .then(response =>{ // Handling the response }).catch(err => { // Handle error }) Example In the following program, we create a script to send data using the custom Request object. So for that, we create a custom request object using the Request() constructor which takes two parameters: the URL(resource URL) and optional. Where the optional parameter contains the customized setting for the request and they are − method − Here we use the POST method which represents that we are sending data to the server. body − Contains the data which we want to send. headers − It tells that the data is JSON data. Now we pass the request object in the fetch() function to send the request and handle the response returned by the server and handle the error if it occurs. <!DOCTYPE html> <html> <body> <script> // Customize setting of the request const optional = { // Setting POST request method: “POST”, // Add body which contains data body: JSON.stringify({ id: 311, title: “Tom like Oranges”, age: 37 }), // Setting header headers:{“Content-type”: “application/json; charset=UTF-8”} }; // Creating request object const newRequest = new Request(“https://jsonplaceholder.typicode.com/todos”, optional); fetch(newRequest) // Handling response .then(response => response.json()) .then(returnData => { console.log(“Data Sent Successfully”); // Display output document.getElementById(“sendData”).innerHTML = JSON.stringify(returnData); }) // Handling error .catch(err=>{ console.error(“We get an error:”, err); }); </script> <h2>Fetch API Example</h2> <div> <!– Displaying retrieved data–> <p id=”sendData”></p> </div> </body> </html> Output Conclusion So this is how we can create a custom request object with the help of the Request interface. This interface provides various properties and methods to modify the request body according to our needs. Now in the next article, we will learn how to upload files using fetch API. Print Page Previous Next Advertisements ”;
Fetch API – Send JSON Data
Fetch API – Send JSON Data ”; Previous Next Fetch API is used to send or receive data asynchronously without refreshing the web page. In the Fetch API, we can send data in various formats like JSON, URL-encoded form, Text, FormData, Blob or ArrayBuffer. Among all these forms JSON (JavaScript Object Notation) data is the most commonly used format to send data using Fetch because it is simple, lightweight, and compatible with most of the programming languages. JSON data is generally created in the following format − Const JSONData = { name: “Monika”, Id: 293, Age: 32, City: “Pune” }; Where name, id, Age, and City are the properties and Monika, 293, 32, and Pune are their values. Fetch API generally sends JSON data as a payload in the request body or can be received in the response body. And the data is serialized as a string because it is easy to transmit data from one system to another. While working with JSON data, Fetch API perform two main operations on JSON data − Serializing − While sending JSON data in a request we need to convert the value into JSON string format using the “JSON.stringify()” function. This function takes an object or value as an input parameter and returns a string which represents JSON format. Due to serializing data, we can easily transmit data over the network. Syntax JSON.stringify() Parsing − Parsing is a process in which we convert the JSON string received in the response back into the JavaScript object or value. This parsing of JSON data can be done by using the response.json() function. This function takes the response object as an argument and returns a promise which is resolved in the parsed JSON data or JavaScript object. Syntax response.json() Send JSON Data To send JSON data Fetch API uses the following ways − Using fetch() function Using the fetch() function with async/await Using request object Method 1 − Using the fetch() function We can send data using the fetch() function. In this function, we create JSON data in the body parameter and use the POST request method to send data on the specified URL. Example In the following program, we will send JSON data using the fetch() function. The fetch() function is used to create a request. The request contains the POST method which tells us that we want to send data, a body which contains JSON data which is converted into a string using stringify() and the header which specifies that we are sending JSON data. After sending the request the server returns a promise which will resolve to a Response object and using .json() we parse the JSON data and display the result in the console log. If we encounter an error, then the error is handled by the catch block. <!DOCTYPE html> <html> <body> <script> // Sending JSON data using a POST request fetch(“https://jsonplaceholder.typicode.com/todos”, { // Setting POST request method: “POST”, // Add a body which contains JSON data body: JSON.stringify({ id: 290, title: “Today is the rainy day”, }), // Setting headers headers:{“Content-type”: “application/json; charset=UTF-8”} }) // Converting response to JSON .then(response => response.json()) .then(myData => { console.log(“Data Sent Successfully”); // Display output in HTML page document.getElementById(“sendData”).innerHTML = JSON.stringify(myData); }) .catch(err=>{ console.error(“We get an error:”, err); }); </script> <h2>Sent Data</h2> <div> <!– Displaying data–> <p id = “sendData”></p> </div> </body> </html> Output Method 2 − Using fetch() function with async/await We can also send JSON data using the fetch() function with async/await. Async/await allows you to create an asynchronous program which behaves more like a synchronous program which makes it easier to learn and understand. Example In the following program, we will send JSON data using the fetch() function with async/await. So for that, we create an async function. In the function, we use try block which uses the fetch() function along with the resource URL, the POST request method, header, and body(JSON data in string format) parameters to send JSON data to the given URL. It also uses await keyword with the fetch() function which is used to wait for the response from the server. If the response is a success, then we parse the response return by the server using the .json() function. If the status code of the response contains an unsuccessful code the else block runs. If we encounter an error during the fetch operation, then that error is handled by the catch block. <!DOCTYPE html> <html> <body> <script> async function sendingJSONData(){ try{ const retrunResponse = await fetch(“https://jsonplaceholder.typicode.com/todos”, { // Setting POST request to send data method: “POST”, // Add body which contains JSON data body: JSON.stringify({ id: 290, title: “Today is the rainy day”, }), // Setting headers headers:{“Content-type”: “application/json; charset=UTF-8”} }); if (retrunResponse.ok){ // Handling response const returnData = await retrunResponse.json(); console.log(“Data send Successfully”); // Display output in HTML page document.getElementById(“sendData”).innerHTML = JSON.stringify(returnData); } else { console.log(“We found error”, retrunResponse.status); } } catch(err) { // Handling error if occur console.error(“Error is:”, err) } } sendingJSONData(); </script> <h2>Sent Data</h2> <div> <!– Displaying data–> <p id = “sendData”></p> </div> </body> </html> Output Method 3 − Using request object We can also send JSON data using a request object. It is an alternative to the fetch() function to send requests to the server. The request object also uses the POST method to send JSON data on the specified URL. The request object is created by using the Request() constructor of the Request interface. The request object provides more flexibility in creating or configuring the request before sending it by the fetch() function. It also allows us to add additional options like header, caching, request method, etc. Example In the following program, we will send JSON data using a request
AJAX – Useful Resources
Ajax – Useful Resources ”; Previous Next The following resources contain additional information on Ajax. Please use them to get more in-depth knowledge on this topic. Useful Video Courses JQuery Masterclass Course: JavaScript And AJAX Coding Bible 73 Lectures 4.5 hours Frahaan Hussain More Detail AJAX API JSON Connect to JSON data using AJAX webpage Most Popular 21 Lectures 1 hours Laurence Svekis More Detail The Complete Web Development Course 201 Lectures 18.5 hours Metla Sudha Sekhar More Detail Learn XML-AJAX – A Course For Beginners 30 Lectures 2 hours YouAccel More Detail Create a Members Only Blog using PHP, MySQL & AJAX 21 Lectures 1.5 hours YouAccel More Detail Fundamentals of Ajax, jQuery and JSON Online Course 18 Lectures 2.5 hours Stone River ELearning More Detail Print Page Previous Next Advertisements ”;
Fetch API – Headers
Fetch API – Headers ”; Previous Next Fetch API provides a special interface known as the Headers interface to perform various operations like setting, adding, retrieving and removing headers from the request and response”s headers list. The Headers objects are initially empty or may contain zero or more name-value pairs. You can add header names in the headers object using the append() method. This interface provides various methods to perform actions on the Headers object. Constructor To create a headers object we can use the Headers() constructor along with a new keyword. This constructor may or may not contain parameters. Syntax const newHeader = New Headers() Or const newHeader = New Headers(init) The Headers() constructor contains only one optional parameter that is init. It is an object which contains HTTP headers that you want to pre-populate your headers object. The value of this parameter is a string value or an array of name-value pairs. Example 1 In the following program, we are sending data to the server. So for that, we create a new headers object using the Header() constructor and then add name-value pairs using the append() function. After that, we make a fetch() request with the fetch() function which includes the POST method, the headers object that we created earlier to add headers to the request, and the body of the request. Now, after sending the request to the server now we use the then() function to handle the response. If we encounter an error, then that error is handled by the catch() function. <!DOCTYPE html> <html> <body> <script> // Creating Headers object const myheaders = new Headers(); // Adding headers to the Headers object myheaders.append(”Content-Type”, ”application/json”); myheaders.append(”Authorization”, ”Bearer token123”); // Sending data using POST request fetch(“https://jsonplaceholder.typicode.com/todos”, { // Adding POST request method: “POST”, // Adding headers headers:myheaders, // Adding body which we want to send body: JSON.stringify({ id: 32, title: “Hello! How are you?”, }) }) // Converting received information into JSON .then(response => response.json()) .then(myData => { // Display the sent data console.log(“Data Sent Successfully”); // Display output document.getElementById(“manager”).innerHTML = JSON.stringify(myData); }); </script> <h2>Display Data</h2> <div> <!– Displaying retrevie data–> <p id = “manager”></p> </div> </body> </html> Output Methods The following are the commonly used method of Header interface − Sr.No. Method Name & Description 1 Headers.append() This method is used to append a new value inside the existing headers object. Or it can add a header if it does not exist. 2 Headers.delete() This method is used to delete a header from the Headers object. 3 Headers.enteries() This method provides an iterator which allows us to iterate through all the key/value pairs present in the given object. 4 Headers.forEach() This method executes once for each key/value pair present in the Headers object. 5 Headers.get() This method is used to find all the string sequence of all the values of the header present inside the Header object. 6 Headers.getSetCookie() This method returns an array which contains all the values of Set-Cookie headers related to the response. 7 Headers.has() This method returns a boolean value which checks if the current Headers object contains the specified header or not. 8 Headers.keys() This method is used to iterate through all the keys of the key-value pairs present in the given object. 9 Headers.set() This method is used to set a new value for the existing Headers object. Or can add a header if it doesn”t exist. 10 Headers.values() This method is used to iterate through all the values of the key-value pairs present in the given object. Example 2 In the following program, we use the methods such as append(), get(), keys() and values() provided by the Headers interface. <!DOCTYPE html> <html> <body> <script> // Creating Headers object const myheaders = new Headers(); // Adding headers to the Headers object myheaders.append(”Content-Type”, ”application/json”); myheaders.append(”Authorization”, ”Bearer token123”); // Sending data using POST request fetch(“https://jsonplaceholder.typicode.com/todos”, { // Adding POST request method: “POST”, // Adding headers headers:myheaders, // Adding body which we want to send body: JSON.stringify({ id: 32, title: “Hello! How are you?”, }) }) // Converting received information into JSON .then(response => { // Header also returned in response // Accessing response header const resHeader = response.headers; // Getting content type value of the response header // Using get() function const contentTypeValue = resHeader.get(“Content-Type”); console.log(“Content-Type:”, contentTypeValue); // Getting all the keys present in the // key-value pairs in response header // Using keys() function const headerKeys = resHeader.keys(); for(const res of headerKeys){ console.log(“Keys:”, res); } // Getting all the values present in the // key-value pairs in response header // Using Values() function const headerValues = resHeader.values(); for(const resVal of headerValues){ console.log(“Values:”, resVal); } }); </script> <h2>Fetch API Examples</h2> </body> </html> Output Conclusion So this is how we use the Header interface in Fetch API. It provides various methods to manipulate, access and iterate over the headers. We can also retrieve Header objects from the Request and response using Request.headers and Response.headers properties. Now in the next article, we will learn about the Request interface. Print Page Previous Next Advertisements ”;
AJAX – Browser Compatibility
AJAX – Browser Compatibility ”; Previous Next AJAX creates dynamic webpages in which the communication between the user and the server takes place in the background without loading the whole page. So it is important to know the browser compatibility because different browsers can implement XMLHttpRequest object and its related properties and methods differently. The following are the key points that are used to check the compatibility of the browser − Support XMLHttpRequest”s object − A browser must support the XMLHttpRequest object. Some of the old browser(like internet explorer 6 or earlier versions) does not keep the XMLHttpRequest object. To make them compatible with other browsers you will need to use the fallback approach using iframe or form elements to run all the AJAX functionalities. Cross-origin request − Some browsers don”t support cross-origin requests made using XMLHttpRequest. So to prevent these vulnerabilities we use JSONP(JSON with padding), CORS(Cross-Origin Resource Sharing) or proxy server to do cross-origin requests. Response Type − Distinct browsers may support different response types like text, JSON, XML, binary data, etc, for XMLHttpRequest. So if you want your application to support a wide range of web browsers, you need to find the supported response type and handle it wisely. Error handling − Different browsers handle XMLHttpRequest errors differently. So you need to check your error handling code to ensure that it works well for all browsers. Event Handling − Different browsers may have their own ways of handling events for XMLHttpRequest like onload, etc. So you need to test and then adjust your code to ensure that it works well for all browsers. Although most modern browsers like Google Chrome, Mozilla Firefox, Microsoft Edge, Safari, and Opera fully support AJAX. But some of the older browsers like internet explorer 6 and 7 have limited support of AJAX. So in that, never forget browser compatibility because it will affect the working of the AJAX web application. Conclusion To ensure the compatibility of your AJAX application among all the browsers, you need to use a JavaScript library or framework which provides cross-browser support to AJAX. Also, these libraries help you to remove away the browser-specific differences while handling XMLHttpRequest and give a consistent API for the AJAX request. Now in the next article, we will see the security features provided by AJAX. Print Page Previous Next Advertisements ”;
Stream API – Error Handling
Stream API – Error Handling ”; Previous Next While working with streaming APIs they sometimes return errors due to network interruptions, server-side problems, data transmission, etc. So to handle these errors every API uses their own error-handling mechanisms during the streaming process. It makes the application robust and resilient. So the commonly used error-handling practices are − Error Event Listeners − Almost all the streaming APIs support error event listeners. Error event listeners come into the picture when an error occurs and allow you to handle the error appropriately. It is can used with suitable objects like WebSocket, Fetch API, or ReadableStream. Try-Catch Block − You are allowed to use a try-catch block to handle errors while working with synchronous code in a specific type of stream. Promises and Async/Await − While using Promises or Async/Await with streaming APIs you can use a catch block to handle errors that occur during streaming. Backoff and Retry Method − If your error is not temporary then you can use the backoff and retry method. In this method, the application waits for the data for a short period of time and if the data is not received in that time period then it retries from the failed operation. User-friendly error message − If the error occurs, then provide a simple and user-friendly error message to the end user to avoid displaying technical details that may confuse users and can able to avoid security risks. Data Validation − Always make sure that the incoming data from the streaming API is properly validated and sanitized to avoid data format errors or unexpected data tends to process issues. Conclusion Always thoroughly checks the error handling implementation to make sure that it works properly. Now in the next article, we will learn about body data in the fetch API. Print Page Previous Next Advertisements ”;
Stream API – Response Body
Stream API – Response Body ”; Previous Next In Stream API, the body is a property of the Response interface. It is used to get the body content of ReableStream. It is a read-only property. The response body is not sent in a single body but it sends in small chunks and the client starts processing as soon as it receives data. It does not have to wait till the complete response. Syntax Response.body This property return either ReadableStream or null for any Response object which is created with null body property. Example In the following program, we will see how to use Response Body in Stream API. So for that, we send a GET request using fetch() to the given URL. If the response is successful, then using the response body is obtained as a “ReadableStream” with the help of response.body.getReader(). Then we define a readMyStream() function to read the data chunks received from the stream. If any error occurs, then it is successfully handled by the catch() function. <script> // fetch() function to send GET request fetch(”http://example.com/”) .then(response => { if (response.ok) { // Using body property we get the ReadableStream const myReader = response.body.getReader(); // Using this function we read the chunks function readMyStream() { return myReader.read().then(({ done, value }) => { if (done) { // Stream is completed return; } // Process the data from the chunks const receivedData = new TextDecoder().decode(value); console.log(receivedData); // Continue reading return readMyStream(); }); } return readMyStream(); } }) .catch(error => { // Handling error console.log(”Found Error:”, error); }); </script> Conclusion So this is how the Response Body body works. Before using the Response body always check if the specified API supports streaming responses or not. Because not all the APIs support streaming responses. Now in the next article, we will learn about byte readers in Stream API. Print Page Previous Next Advertisements ”;