如何使用 JavaScript 在 Hackerrank 中发出 AJAX 请求? [英] How to make AJAX request in Hackerrank using JavaScript?
问题描述
我打开 Hackerrank 示例测试并尝试使用可能用于进行 AJAX 调用的方法.XMLHttpReq
、fetch
等.它们都不起作用;XHR
和 fetch
方法不可用.
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.
第一次获取
:
async function myFetch() {
let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
let data = await response.json();
console.log(data);
}
Hackerrank 抛出错误,因为 fetch
不是函数.我也试过 window.fetch
和 global.fetch
无济于事.
Hackerrank throws an error because fetch
is not a function. I also tried window.fetch
and global.fetch
to no avail.
我试过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 说 XMLHttpRequest
未定义.
Hackerrank says XMLHttpRequest
is not defined.
Hackerrank 正在执行 Node.JS 代码,这就解释了为什么 XHR
不可用,也许我必须要求自己.除了我不能 npm install
任何东西,我只能访问他们的小 IDE.
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.
如何在这个平台上使用 JavaScript 进行 AJAX 调用?
How do you make an AJAX call in this platform with JavaScript?
推荐答案
我已经通过了 HackerRank REST API 认证并且遇到了同样的问题.HackerRank 使用 NodeJs 环境来运行您的代码(在语言选择中说),因此 XMLHttpRequest 和 fetch 都不可用(因为它们仅适用于浏览器).
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 ).
我建议你使用 request
npm 包,HackerRank 允许你需要它.一个缺点是 request 不支持 Promises &除非您导入其他包(HackerRank 似乎无法识别),否则异步/等待.
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).
这是我用过的:
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.
这篇关于如何使用 JavaScript 在 Hackerrank 中发出 AJAX 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!