简体   繁体   中英

How to make AJAX request in Hackerrank using JavaScript?

I open the Hackerrank example test and play around with methods one might use to make an AJAX call. XMLHttpReq , fetch , etc. None of them work; XHR and fetch methods are unavailable.

First fetch :

async function myFetch() {
  let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  let data = await response.json();
  console.log(data);
}

Hackerrank throws an error because fetch is not a function. I also tried window.fetch and global.fetch to no avail.

I tried XHR :

function myXHR() {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
      console.log(this.responseText);
      // or JSON.parse(this.responseText);
    }
  };
  xmlhttp.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');
  xmlhttp.send();
}

Hackerrank says XMLHttpRequest is not defined.

Hackerrank is executing Node.JS code, that explains why XHR isn't available, I have to require myself perhaps. Except I can't npm install anything, all I have access to is their little IDE.

How do you make an AJAX call in this platform with JavaScript?

I've passed the HackerRank REST API certification and had the same issue. HackerRank uses a NodeJs environnement to run you code (it's said in the langage selection), so neither XMLHttpRequest nor fetch are available ( as these are Browser only ).

I suggest you use the request npm package , HackerRank allows you to require it. One downside is that request doesn't support Promises & Async/Await unless you import other packages (which HackerRank doesn't seem to recognize).

Here's what I used :

const request = require('request');

function myFetch(url) {
  return new Promise((resolve, reject) => {
    request(url, function (error, response, body) {
      if(error) reject(error)

      else resolve(body)
    });
  });
}

Note : request package has been recently deprecated, but it will still work well for your use case.

I have given a test in HackerRank recently and I have used the node.js native module for http / https to fetch data from an API. As you can use this without requiring any external libraries.

also, if you need to create promises you can create your own wrapping over the https implementation.

Try using this:

async function fetchData(url) {
    const https = require('https');
    return new Promise((resolve, reject) => {
        https.get(url, (response) => {
            let data = '';

            response.on('data', (stream) => {
                data += stream;
            })

            response.on('end', () => {
                const resolvedData = JSON.parse(data);
                resolve(data);
            })
        }).on('error', (err) => {
            reject(err);
        })
    });
}

async function showData() {
    const data = await fetchData('https://jsonmock.hackerrank.com/api/movies?Year=2000');
    console.log(data);
}

showData();

this can solve your problem in HackerRank. This example is only given for a get request. For all other Methods please try using the options from https module of Node.js .

Hackerrank currently uses node version 14.x.xx which comes with axios . All you have to do is scroll to the top and import or require axios, then you can make use of axios.get() or axios.post() as the case may be.

  • Hackerrank currently uses node version 14.x.xx which comes with Axios

Example for get call:
a) const axios = require('axios');
b) let response = await axios.get('URL here');

In the same way, you can use all HTTP Methods.

let url = 'https://someurl.com/api/article_users?username=username';
const https = require('https');

https.get(url, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);

res.on('data', (d) => {
    process.stdout.write(d);
});

}).on('error', (e) => {
console.error(e);
});

This worked for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM