DEV Community

Cover image for HTTP request in Javascript?
Vitalii Sevastianov
Vitalii Sevastianov

Posted on • Updated on

HTTP request in Javascript?

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();
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode
const request = require('superagent');
request
  .get('https://example.com')
  .end((err, res) => {
    if (err) { console.log(err); }
    console.log(res.text);
  });
Enter fullscreen mode Exit fullscreen mode

Also, you can use async/await feature with fetch or libraries such as axios or superagent to make your code more readable.

Top comments (0)