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

Time:06-13

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.

CodePudding user response:

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

CodePudding user response:

suggestion: using async await

const axios = require('axios');

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