Stream API – Readable Streams

Stream API – Readable Streams ”; Previous Next In Stream API, a readable stream is a data source from where we can read data in a sequential and asynchronous way. It is a standardized way to get data from the underlying sources. Underlying sources is the resource which present on the network. They are of following two types − Push source − In which the data is pushed to you when you access them. You can have control of the stream like when to start or when to pause or even when to terminate the current stream. For example, video game streaming. Pull source − In which you need to explicitly request the data from them. For example access files with the help of Fetch or XHR call. In a Readable Stream, the data is in the form of small chunks so it is read sequentially, one chunk at a time. A chunk can be a single byte or can be of a larger size. Hence the size of the chunks can be different in a stream. Now lets us understand how readable stream works. Working of Readable Stream The working of the Readable stream is quite straightforward. In a readable stream, the chunks of data are placed in enqueue. It means the chunks are waiting in the queue to read. Here we have another queue that is an internal queue which keeps track of unread chunks. The chunks are read by the reader. It processes the data of one chunk at a time and allows you to perform operations on the data. One reader can read only a single stream at a time. When the reader starts reading the stream at that time the stream is locked for that reader means no other reader is allowed to read that stream. If you want another reader to read that stream, then you have to terminate the first reader or can create a tee stream. Also, each reader has its own controller which allows you to control the stream such as start, close, or pause. It also has a consumer who is responsible for handling the received data from the readable stream and processing it and can able to perform operations on it. Readable Stream Interfaces Stream API supports three types of readable stream interfaces − ReableStream Interface ReableStreamDefaultReader Interface ReadableStreamDefaultController Interface ReadableStream Interface The ReadableStream Interface is used to represent a readable stream of data. It is generally used with Fetch API to handle the response stream. It can also handle the response stream of developer-defined streams. Constructor To create a readable stream object for the given handlers ReadableStream interface provides a ReadableStream() constructor. Syntax const newRead = new ReadableStream() Or const newRead = new ReadableStream(UnderlyingSource) Or const newRead = new ReadableStream(UnderlyingSource, QueuingStrategy) Following are the optional parameters of the ReadableStream() constructor − UnderlyingSource − This object provide various methods and properties that define the behaviour of the stream instance. The methods are: start(), pull(), and cancel() whereas the properties are: type and autoAllocateChunkSize. QueuingStrategy − This object is used to define the queuing strategy for the given streams. It takes two parameters: highWaterMark, and size(chunk). Instance Properties The properties provided by the ReadableStream interface are read-only properties. So the properties provided by ReadableStream are − Sr.No. Property & Description 1 ReadableStream.locked This property is used to check whether the readable stream is locked to a reader or not. Methods The following are the commonly used method of the ReadableStream interface − Sr.No. Method & Description 1 ReadableStream.cancel() This method returns a promise which will resolve when the stream is cancelled. 2 ReadableStream.getReader() This method is used to create a reader and locks the stream to it. No other reader is allowed until this reader is released. 3 ReadableStream.pipeThrough() This method is used to create a chainable way of piping the current stream through a transform stream. 4 ReadableStream.pipeTo() This method is used to pipe the current ReadableStream to the given WriteableStream. It will return a promise when the piping process completes successfully or reject due to some error. 5 ReadableStream.tee() This method is used to get a two-element array which includes two resulting branches as new ReadableStream objects. ReadableStreamDefaultReader Interface The ReadableStreamDefaultReader interface is used to represent a default reader which will read stream data from the network. It can also be read from ReadableStream. Constructor To create a readableStreamDefualtReader object ReadableStreamDefaultReader interface provides a ReadableStreamDefaultReader() constructor. Syntax const newRead = new ReadableStreamDefaultReader(myStream) This constructor contains only one parameter which is myStream. It will read ReadableStream. Instance Properties The properties provided by the ReadableStreamDefaultReader interface are read-only properties. So the properties provided by ReadableStreamDefaultReader are − Sr.No. Property & Description 1 ReadableStreamDefaultReader.closed This property returns a promise which will resolve when the stream is closed or rejected due to some error. It allows you to write a program which will respond at the end of the streaming process. Methods The following are the commonly used method of the ReadableStream interface − Sr.No. Method & Description 1 ReadableStreamDefaultReader.cancel() This method returns a promise which will resolve when the stream is cancelled. 2 ReadableStreamDefaultReader.read() This method returns a promise which will give access to the next chunk or piece in the stream”s queue. 3 ReadableStreamDefaultReader.releaseLock() This method is used to remove the lock of the reader on the stream.

Stream API – Basics

Stream API – Basics ”; Previous Next Stream API allows developers to access the streams of data received over the network and process them bit-by-bit according to their needs with the help of JavaScript programming language. Where the streams are the sequence of data that we want to receive over the network in small chunks and then we process that small chunks in bit-by-bit. Before streaming, if we want to process a video, audio, or text file we need to download that complete file from the network and wait for it to be deserialized into a specified format and then process the complete downloaded file. After the introduction of streams, the whole working culture is changed now we can start processing data bit-by-bit as soon as the data is received on the client side using JavaScript without creating any extra buffer or blob. Using streams we can perform various tasks like can find the start and end of the stream or can chain streams together or can easily handle errors, can cancel the streams, and much more. Streaming is used to create real-world applications like video streaming applications like Netflix, Amazon Prime Videos, Zee5, Voot, YouTube, etc. So that users can easily watch movies, TV shows, etc. online without downloading them. Stream API provides various features like ReadableStream, Teeing, WritableStream, Pipe Chains, Backpressure, internal queue, and queueing strategies. Let”s discuss them one by one in detail. Readable Stream The readable stream allows you to read data/chunks from the source in JavaScript using the ReadableStream object. The chunks are small pieces of data that are going to be read by the reader sequentially. It can be of a single bit or can be of a large size like a typed array, etc. To read a readable stream API provide a reader. It reads chunks from the stream and then processes the data of the chunk. Only one reader can read a stream at a time, no other reader is allowed to read that stream. Writable Stream The writable stream allows you to write data in JavaScript using the Writable Stream object. The data is written by the writer to the stream. The writer writes data in the form of chunks(one chunk at a time). When the writer is created and starts writing to the stream for that time the stream is locked for that writer, and no other writer is allowed to access that stream and an inter queue is used to keep track of the chunks written by the writer. Teeing Teeing is a process in which a stream is split into two identical copies of the stream so that two separate readers can read the stream at the same time. We can achieve teeing with the help of the ReableStream.tee() method. This method returns an array that contains two identical copies of the specified stream and can be read by two readers. Pipe Chains Pipe Chain is a process in which multiple streams are connected together to create a data processing flow. In Stream API, we can pipe one stream into another with the help of a pipe chain structure. The starting point of the pipe chain is known as the original source and the last point of the pipe chain is known as the ultimate sink. To pipe streams we can use the following methods − ReadableStream.pipeThrough() − This method is used to pipe the current stream through a transform stream. Transform stream contains a pair of readable and writable streams. ReadableStream.pipeTo() − This method is used to pipe the current ReadableStream to the specified WritableStream and will return a promise which resolves when the piping process is successfully completed or rejected due to some error. Backpressure Backpressure is a special concept in Stream API. In this process, a single stream or pipe chain controls the speed of read/write. Suppose we have a stream, this stream is busy and does not able to take new chunks of data, so it sends a backward message through the chain to tell the transform stream to slow down the delivery of chunks so that we can save from bottleneck. We can use backpressure in the ReadableStream, so we need to find the chunk size required by the consumer with the help of the ReadableStreamDefaultContriller.desiredSize property. If the chunk size is very low, then the ReadableStream can indicate it”s an underlying source so stop sending more data and send backpressure along with the stream chain. When the consumer again wants the received data then we use the pull method to tell the underlying source to send data to the stream. Internal queues and queuing Strategies Internal queues are the queues that keep track of those chunks that have not been processed or finished. For example, in a readable stream, the internal queue keeps track of those chunks that are present on the enqueue but not read yet. Internal queues use a queueing strategy representing how the backpressure signal sends according to the internal queue state. Conclusion So these are the basic concept of Stream API. It is generally used in online streaming. When you watch a video online the browser or the application receives continuous streams of data chunks in the background and then they are processed by that browser or the application to display the video. Now in the next article, we will learn about the Readable stream of Stream API. Print Page Previous Next Advertisements ”;

AJAX – Quick Guide

AJAX – Quick Guide ”; Previous Next What is AJAX? AJAX stands for asynchronous Javascript and XML. AJAX is not a programming language or technology, but it is a combination of multiple web-related technologies like HTML, XHTML, CSS, JavaScript, DOM, XML, XSLT and XMLHttpRequest object. The AJAX model allows web developers to create web applications that are able to dynamically interact with the user. It will also be able to quickly make a background call to web servers to retrieve the required application data. Then update the small portion of the web page without refreshing the whole web page. AJAX applications are much more faster and responsive as compared to traditional web applications. It creates a great balance between the client and the server by allowing them to communicate in the background while the user is working in the foreground. In the AJAX applications, the exchange of data between a web browser and the server is asynchronous means AJAX applications submit requests to the web server without pausing the execution of the application and can also process the requested data whenever it is returned. For example, Facebook uses the AJAX model so whenever we like any post the count of the like button increase instead of refreshing the whole page. Working of AJAX Traditional web applications are created by adding loosely web pages through links in a predefined order. Where the user can move from one page to another page to interact with the different portions of the applications. Also, HTTP requests are used to submit the web server in response to the user action. After receiving the request the web server fulfills the request by returning a new webpage which, then displays on the web browser. This process includes lots of pages refreshing and waiting. AJAX change this whole working model by sharing the minimum amount of data between the web browser and server asynchronously. It speedup up the working of the web applications. It provides a desktop-like feel by passing the data on the web pages or by allowing the data to be displayed inside the existing web application. It will replace loosely integrated web pages with tightly integrated web pages. AJAX application uses the resources very well. It creates an additional layer known as AJAX engine in between the web application and web server due to which we can make background server calls using JavaScript and retrieve the required data, can update the requested portion of a web page without casing full reload of the page. It reduces the page refresh timing and provides a fast and responsive experience to the user. Asynchronous processes reduce the workload of the web server by dividing the work with the client computer. Due to the reduced workload web servers become more responsive and fast. AJAX Technologies The technologies that are used by AJAX are already implemented in all the Morden browsers. So the client does not require any extra module to run the AJAX application.The technologies used by AJAX are − Javascript − It is an important part of AJAX. It allows you to create client-side functionality. Or we can say that it is used to create AJAX applications. XML − It is used to exchange data between web server and client. The XMLHttpRequest − It is used to perform asynchronous data exchange between a web browser and a web server. HTML and CSS − It is used to provide markup and style to the webpage text. DOM − It is used to interact with and alter the webpage layout and content dynamically. Advantages of AJAX The following are the advantages of AJAX − It creates responsive and interactive web applications. It supports the development of patterns and frameworks that decrease the development time. It makes the best use of existing technology and feature instead of using some new technology. It makes an asynchronous call to the web server which means the client doesn”t have to wait for the data to arrive before starting rendering. Disadvantages of AJAX The following are the disadvantages of AJAX − AJAX is fully dependent on Javascript. So if anything happens with javascript in the browser AJAX will not support. The debugging of AJAX applications is difficult. Bookmarking of AJAX-enabled pages required pre-planning. If one request can fail then it can fail the load of the whole webpage. If JavaScript is disabled in your web browser then you are not able to run the AJAX webpage. Conclusion So to create dynamic web pages or applications AJAX is the best choice. It is faster and more responsive and provides asynchronous interaction between the client and server without refreshing the whole page. Now in the next article, we will see the history of AJAX. Ajax – History Before the introduction of AJAX, websites are developed by adding multiple loose web pages together, which are further displayed in a predefined order with the help of links embedded inside the HTML pages. So to use these web application user needs to move from one web page to another web page. So whenever the user clicks on a link to the next page he/she should wait for some seconds for a page to be loaded. Traditional web applications use HTTP requests to submit user action to the server. After receiving the request from the user the web server completes the request by returning a new web page which will further display on the web browser. Hence traditional web applications required lots of page refreshes and waiting. Due to this, it is very hard to develop new-generation applications like google maps, real-time chatting environment, Gmail, etc. So on 18 February 2005 for the first time, Jesse James Garrett introduce AJAX to the world by writing an AJAX article named “A New Approach to Web Application”. And on 5th April 2006, the W3C(world wide web consortium) release the first draft which contains the specifications for the XMLHttpRequest object. After that AJAX will be popular among web developers. The

AJAX – Discussion

Discuss AJAX ”; Previous Next AJAX is a web development technique for creating interactive web applications. If you know JavaScript, HTML, CSS, and XML, then you need to spend just one hour to start with AJAX. Print Page Previous Next Advertisements ”;

Stream API – Request Object

Stream API – Request Object ”; Previous Next The request object is used to fetch resources from the server. A request object is created by using Resquest() constructor provided by the Resquest interface. So when the new Request object is created we are allowed to pass a ReadableStream to the body of the Request object such types of requests are known as streaming requests. This request object is then passed to the fetch() function to fetch the resources. Syntax const myobject = new Request(URL, { method: ”POST”, body: Stream, headers: {”Content-Type”}, duplex: ”half”, }); Here the Request() constructor contains the following parameters − URL − Address of the resource. method − It represents the HTTP request method like GET, POST, etc. body − Contains the ReadableStream object. headers − Contains the suitable headers for the body. duplex − Set to half to make duplex stream. Example In the following program, we create a streaming request. So for that first we create a readable stream with the help of the ReadableStream() constructor along with the start() function which implements the ReadableStream logic and other operations. Then we create a request object using the Request() constructor along with the options: the method option contains the POST request to send the request, the body option contains the stream, the headers option contains the appropriate header, and the duplex option is set to half to make it a duplex stream. After creating a request object now we pass the object in the fetch() function to make a request and this function handles the response using then() and an error(if occurs) using the catch() function. Here in place of https://exampleApi.com/, you can use a valid API/URL which sends/receive data in the form of chunks. <script> // Create a readable stream using the ReadableStream constructor() const readStream = new ReadableStream({ start(controller) { // Here implement your ReadableStream // Also with the help of controller, you can enqueue data and // signal the end of the stream }, }); // Create a request objecct using Request() constructor const request = new Request(”https://exampleApi.com/”, { // Set the method method: ”POST”, // Passing the stream to the body of the request body: stream, // Setting suitable header headers: {”Content-Type”: ”application/octet-stream”}, duplex: ”half” }); // After creating a request object pass the object // to fetch() function make a request or perform operations fetch(request) .then(response => { // Handling the response }) .catch(error => { // Handling any errors if occur }); </script> Restrictions Streaming requests is a new feature so it has some restrictions and they are − Half duplex − To execute a streaming request we have to set the duplex option to half. If you do not set this option in your streaming request, then you will get an error. This option tells that the request body is a duplex stream, where the duplex stream is a stream which receives data(writeable) and sends data(readable) simultaneously. Required CORS and trigger a preflight − As we know that a streaming request contains a stream in the request body but does not have a “Content-Length” header. So for such type of request, CORS is required and they always trigger a preflight. Also, no-cors streaming requests are not allowed. Does not work on HTTP/1.x − If the connection is HTTP/1.x, then based on the HTTP/1.x rules it will reject fetch. According to the HTTP/1.x rules, the request and response bodies should need to send a Content-Length headers. So that the other party can keep a record of how much data is received or can change the format to use chunked encoding. Chunked encoding is common but for the requests, it is very rare. Server-side incompatibility − Some servers do not support streaming requests. So always use only those servers that support streaming requests like NodeJS, etc. Conclusion So this is how we can create a Request object for streams or we can say that this is how we can create a streaming request using the fetch() function. Streaming requests are useful for sending large files, real-time data processing, media streaming, continuous data feeds, etc. Now in the next article, we will learn about the response body in Stream API. Print Page Previous Next Advertisements ”;

AJAX – Examples

AJAX – Examples ”; Previous Next Here is a list of some famous web applications that make use of AJAX. Google Maps A user can drag an entire map by using the mouse, rather than clicking on a button. https://maps.google.com/ Google Suggest As you type, Google offers suggestions. Use the arrow keys to navigate the results. https://www.google.com/webhp?complete=1&hl=en Gmail Gmail is a webmail built on the idea that emails can be more intuitive, efficient, and useful. https://gmail.com/ Yahoo Maps (new) Now it”s even easier and more fun to get where you”re going! https://maps.yahoo.com/ Difference between AJAX and Conventional CGI Program Try these two examples one by one and you will feel the difference. While trying AJAX example, there is no discontinuity and you get the response very quickly, but when you try the standard GCI example, you would have to wait for the response and your page also gets refreshed. AJAX Example * = Standard Example * = NOTE − We have given a more complex example in AJAX Database. Print Page Previous Next Advertisements ”;

Fetch API – Send PUT Requests

Fetch API – Send PUT Requests ”; Previous Next In the Fetch API, a PUT request is used to update or replace the existing resource or data present on the server. Using the PUT request generally contains the data which you want to update in the body of the request. When the request is received by the server, the server uses that data to update the existing resource present in the given URL. If the server does not contain the resource then it creates a new resource using the given data. Syntax fetch(URL, { method: “PUT”, body: {//JSON Data}, headers:{“content-type”: “application/json; charset=UTF-8”}}) .then(info =>{ // Code }) .catch(error =>{ // catch error }); Here the fetch() function contains the following parameters − URL − It represents the resource which we want to fetch. method − It is an optional parameter. It is used to represent the request like, GET, POST, DELETE, and PUT. body − It is also an optional parameter. You can use this parameter when you want to add a body to your request. headers − It is also an optional parameter. It is used to specify the header. Example 1: Sending PUT Request Using fetch() In the following program, we create a simple script to update existing data in the given URL using the PUT request using the fetch() function. Here we send a JSON document in the given URL along with the header. So after receiving the response, check the status of the response. If the response status is 200, then that means the data is updated successfully. If an error occurred, then the catch function handles that error. <!DOCTYPE html> <html> <head> <title>Fetch API Example</title> </head> <body> <h1>Example of Fetch API</h1> <script> // Update data in the URL using the PUT request fetch(“https://jsonplaceholder.typicode.com/todos/21”, { // Using PUT request method: “PUT”, // Body contains replacement data body: JSON.stringify({ id: 22, title: “Hello! Mohina what are you doing?”, }), // Setting headers headers:{“Content-type”: “application/json; charset=UTF-8”} }) .then(response => { // Handle response if (response.status == 200){ console.log(“Data updated successfully”) } else { throw new error(“Error Found:”, response.status) } }) // Handle error .catch(err=>{ console.error(err) }); </script> </body> </html> Output Example 2: Sending PUT Request Using fetch() with async/await In the following program, we create a script to update existing data in the given URL using the PUT request with the fetch() function and async/await. Here we send a JSON document in the given URL along with the header. So we create an async function named modifyData(). Here we use await keyword with the fetch() function to pause the execution of the function until the returned promise is resolved. After receiving the response, check the status of the response if the response status is 200, then that means the data is updated successfully. If an error occurred, then the catch function handles that error. Note − Here async/ await is used together to handle asynchronous operations in a synchronous way. <!DOCTYPE html> <html> <head> <title>Fetch API Example</title> </head> <body> <h1>Example of Fetch API</h1> <script> async function modifyData(){ try{ const myRes = await fetch(“https://jsonplaceholder.typicode.com/todos/21”, { // Using PUT request method: “PUT”, // Body contains replacement data body: JSON.stringify({ id: 24, title: “Mina leaves in Delhi”, }) }); // Handling response if (myRes.status == 200){ console.log(“Data updated successfully”) } else { throw new error(“Error Found:”, myRess.status) } } catch(err){ console.error(err) } } // Calling the function modifyData(); </script> </body> </html> Output Conclusion So this is how we can use PUT requests to update the existing data in the given resource. Using this you can also add extra properties to the request with the help of the parameters provided by the fetch() function. Now in the next chapter, we will see how we will send JSON data. Print Page Previous Next Advertisements ”;

Fetch API – Body Data

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 ”;

Fetch API – Handling Binary Data

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