How to make an HTTP request in Javascript?

  • Share this:
How to make an HTTP request in Javascript?


JavaScript is a cross-platform, object-oriented scripting language used to make webpages interactive, mainly used as a frontend technology for building webpages and apps. 

Also Read: Understanding JavaScript For Loops

The interaction between the frontend and backend of websites is made possible through HTTP requests. Functionalities like updating a record in the database, creating a new record, deleting a picture, and so on, all require an interaction between a server and a client to modify data.

HTTP requests can be used to send or receive data from a server side resource. In this snippet, we'll cover the XMLHttpRequest and fetch API to make HTTP requests in JavaScript.

Also Read: JavaScript Array Map method

Here's an example using XMLHttpRequest

var xhr = new XMLHttpRequest();"GET", "", true); 
xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { console.log(xhr.responseText); } }; 

And here's an example using fetch API

Also Read: Best Youtube channels to Learn JavaScript

.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
TWT Staff

TWT Staff

Writes about Programming, tech news, discuss programming topics for web developers (and Web designers), and talks about SEO tools and techniques