Ads

Tuesday, January 10, 2023

How do I make an HTTP request in Javascript?

 

There are several ways to make an HTTP request in JavaScript, but the most common methods include using the XMLHttpRequest object, or the fetch() API.

Here's an example of using the XMLHttpRequest object to make a GET request to a server:

var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://example.com', true); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { // Request is successful and data is received console.log(xhr.responseText); } }; xhr.send();

Here is an example of using the fetch() API to make a GET request:

fetch('https://example.com') .then(response => response.text()) .then(data => console.log(data)) .catch(error => console.error(error));

Note that in fetch API a response stream is returned, and you need to use methods like text(), json() to extract the data out of it.

Both of these examples make a GET request to the specified URL, and upon receiving a successful response, log the response data to the console. You can modify the request method and data as well as handling the error accordingly.

No comments:

Why perfume is very important in our daily life

  A personal item that can have a significant impact on one's day-to-day life is perfume. It can help set the mood, boost con...