HTTP request in Javascript?
Vitalii Sevastianov
Posted on January 18, 2023
There are several ways to make an HTTP request in JavaScript, but the most commonly used method is the XMLHttpRequest object, which is built into most modern web browsers.
Here's an example of how to use XMLHttpRequest to make a GET request to a specified URL:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com', true);
xhr.send();
You can also use the fetch() method which is more modern and easier to use
fetch('https://example.com')
.then(response => response.text())
.then(data => console.log(data))
You can also use libraries such as axios or superagent to handle http requests.
axios.get('https://example.com')
.then(response => console.log(response.data))
const request = require('superagent');
request
.get('https://example.com')
.end((err, res) => {
if (err) { console.log(err); }
console.log(res.text);
});
Also, you can use async/await feature with fetch or libraries such as axios or superagent to make your code more readable.
💖 💪 🙅 🚩
Vitalii Sevastianov
Posted on January 18, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.