How do I make an HTTP request in Javascript?

Developerking
1 min readJan 13, 2023

There are several ways to make an HTTP request in JavaScript, but the most common way is to use the XMLHttpRequest object, which is built into most web browsers. Here's an example of how you might use it to send a GET request to an endpoint:

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

In this example, xhr.open is used to open a GET request to the specified URL. The onreadystatechange event is used to check the status of the request, and when the request is complete, the response text is logged to the console. The xhr.send() method is used to actually send the request.

You can also use the fetch function to make http requests .

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

And also you can use a library like axios,superagent, isomorphic-fetch, etc

import axios from 'axios';
axios.get('https://www.example.com')
.then(response => console.log(response.data))

You can also use the await/async syntax to make the request:

const getData = async() => {
const response = await axios.get('https://www.example.com')
console.log(response.data);
}
getData()

Please note that, you might need to add some headers and pass data while sending the request in many cases, above example just demostrate the basic request.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Developerking
Developerking

Written by Developerking

We are creating the world's largest community of developers & Share knowledgeable contents , So Stay Tuned & Connect with us !! Become a Dev King Member.

No responses yet

Write a response