DEV Community

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

Posted on • Edited 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.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay