Skip to content
Advertisement

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:

JavaScript

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

I tried XHR:

JavaScript

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?

Advertisement

Answer

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 :

JavaScript

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

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement