.clone() method in Javascript

.clone() method in Javascript

why clone()?

Let us understand what does json() method do in JavaScript. We use fetch API for GET, POST, PUT and DELETE requests in JavaScript. json() method is very commonly used when the request is POST. json() method takes JSON as input and parses it to produce a JavaScript object. It doesn't take any parameters and returns a promise that resolves into a JavaScript object. The object can be an array, a string, a number, or an object.

Whenever a client sends an HTTP request to the server using the POST method, the server will respond with one response. The response is commonly referred to as res. Since it is a single response, calling it again in the same request throws TypeError: Failed to execute 'json' on 'Response': body stream already read.

So now, how do we solve this? There exists a clone() method for allowing multiple uses of the body object. Hence we can read a response more than once in sequence. It creates a copy of the current request object.

2.PNG

Whenever we receive a response from the server, the response body might not be a valid JSON object. In that case, res.json() fails with an error like:

Unexpected token X in JSON at position 0

We need to detect the problem, many times we want to see the content of the response sent by the server. Here we can use the res.clone() method and in the above example, it prints the response in the console.

We can also use res.clone() to check if it is sending a proper response using the if statement. If yes, we can call res.json(), else we can print a message saying the wrong response was received to avoid any abrupt termination of the program due to the error.

To conclude, clone() is very useful as it creates a clone of a response object that can be stored in a different variable to use for any other purpose or to detect errors. This document clearly explains the use of clone to create a duplicate of the response:

https://docs.w3cub.com/dom/response/clone