How do I make an HTTP request from Javascript?

 HTTP request from Javascript



In this article, we are going to learn how to make an HTTP(Hypertext Transfer Protocol) request from Javascript. 

In the previous article we are discussed about Different type of HTTP methods and HTTP error code you can checkout this article after read this article.


In the first step we are going to learn how to write a method to make HTTP request and in second step we will see how to call or execute the method and in the last step we will see how to plug the method to html
to print the response. Complete explanation of code you get at the end of the code.


Step 1: Create a method with name "makeHttpRequest" inside "script" tag.

<script>
    function makeHttpRequest(url) {
	fetch(url)
	.then(response => response.json())
	.then(data => {
	   document.getElementById("output").textContent = JSON.stringify(data);
	 })
	 .catch(error => console.error('Request failed', error));
    }
</script>

Step 2: In this setp we will see how to call the method "makeHttpRequest" with url "https://jsonplaceholder.typicode.com/todos/1"

// Call the function with a URL to make the request
makeHttpRequest('https://jsonplaceholder.typicode.com/todos/1');

Step 3: Complete example

<!DOCTYPE html>
<html>
<head>
	<title>HTTP Request Example</title>
</head>
<body>
    <h1>HTTP Request Example</h1>
    <p id="output"></p>
    <script>
        function makeHttpRequest(url) {
            fetch(url)
	    .then(response => response.json())
	    .then(data => {
	    document.getElementById("output").textContent = JSON.stringify(data);
	    })
	    .catch(error => console.error('Request failed', error));
        }
        // Call the function with a URL to make the request
	 makeHttpRequest('https://jsonplaceholder.typicode.com/todos/1');
    </script>
</body>
</html>



Here is what each part of the code does:

  • <!DOCTYPE html>: This is the document type declaration, which tells the browser that this is an HTML document.

  • <html>, <head>, and <body>: These are the main sections of an HTML document. The <html> tag contains the entire HTML document, the <head> tag contains metadata about the document, and the <body> tag contains the visible content of the document.

  • <title>HTTP Request Example</title>: This sets the title of the web page that appears in the browser tab.

  • <h1>HTTP Request Example</h1>: This is a heading that appears on the page.

  • <p id="output"></p>: This is an empty paragraph tag that will be filled with the response data from the HTTP request.

  • <script>...</script>: This is a block of JavaScript code that will be executed by the browser.

  • function makeHttpRequest(url) {...}: This is a function that takes a URL as a parameter and uses fetch() to make an HTTP request to that URL.

  • fetch(url): This is a method that sends an HTTP request to the specified URL and returns a promise that resolves with the response.

  • .then(response => response.json()): This method extracts the JSON data from the response and returns it as a promise.

  • .then(data => {...}): This method takes the JSON data and updates the content of the paragraph tag with the ID "output" by setting its textContent property to the stringified JSON data.

  • .catch(error => console.error('Request failed', error)): This method catches any errors that occur during the HTTP request and logs them to the console.

  • makeHttpRequest('https://jsonplaceholder.typicode.com/todos/1'): This calls the makeHttpRequest() function with a URL to make the request. In this case, the URL is to a JSON API that returns some sample data.

In summary, this code sets up a simple HTML page that uses JavaScript to make an HTTP request to a JSON API and display the response data on the page.


I hope this helps!


In the previous article we are discussed about Different type of HTTP methods and HTTP error code you can checkout this article after read this article.

Post a Comment

0 Comments