yegor256
yegor256

Reputation: 105043

How to make synchronous HTTP GET request in JavaScript with axios?

I'm trying to do something like this:

const axios = require('axios');
function load() {
  const response = axios.get('https://...');
  return response.data;
}

I can't make my function async. I need it to be declared exactly this way and return the data loaded from the URL via GET request.

Upvotes: 1

Views: 229

Answers (2)

Ilijanovic
Ilijanovic

Reputation: 14904

Well you can try using XMLhttprequest:

const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

function syncRequest(url) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, false);
  xhr.send(null);
  return xhr.responseText;
}

(() => {
  const res = syncRequest("https://api.github.com/users/octocat");
})();

It will block until it receives an response

You will need to install the XMLHttprequest package:

https://www.npmjs.com/package/xmlhttprequest

Upvotes: 2

HENOK MILLION
HENOK MILLION

Reputation: 309

suggestion: using async await

const axios = require('axios');

async function load() {
  const response = await axios.get('https://...');
  ...
}

Upvotes: 1

Related Questions