所以请耐心等待,因为我觉得我已经尝试了所有可以尝试的事情。我对 JavaScript 确实很陌生,之前主要使用 C/C++,但对于这些语言我仍然是新手。我尝试在我的 aws services (ec2) 服务器上创建一个页面,当使用 URL 的 get 请求进行访问时,它将使用我的服务器端 API key 并返回从给定 URL 请求的 JSON 数据。我正在使用《英雄联盟》API 和 NodeJs,使用永久启动 *.js、handlebars 和 Express JavaScript。
我觉得值得一提的是,虽然在为类(class)做作业时出现了这个问题,但我已经在不包含该功能的情况下完成了作业。
我尝试以同步和异步方式执行此操作,但它对我不起作用。我觉得这是因为使用 var foo = new XMLHttpRequest 不是将 get 请求从服务器发送到另一个服务器的正确方法。当我尝试使用 Nodejs 找到更好的方法来做到这一点时,我找不到任何对我有意义或我能理解的东西。
请让我知道为什么这是错误的/为什么会损坏以及我如何才能使其不损坏或正确执行。尽管经过几个小时的努力和搜索,我找不到任何类似的堆栈溢出问题。
app.get('/test',function(req,res){
//if(url == undefined){
var url = "https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/RiotSchmick";
//}
var KEY= "REDACTED_FOR_POST";//note I have a functional api
//key that I can correctly use to view data through a browser get request.
var local = new XMLHttpRequest();//this line prevents this page from runnning
local.open("GET", "https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/RiotSchmick?api_key=REDACTED_FOR_POST", false);
//RiotSchmick is used as an example "summoner" name in quick start
local.send(null);
var content = {};//holder for handlebars
content.text = local.responseText;//I expected this to have a string form JSON.
res.render('buffer.handlebars', content);
//buffer.handlebars is one line: {{text}} and properly prints data when
//content.text is assigned to a constant such as "hello"
})
感谢您的帮助和您的时间。
最佳答案
除非您使用类似 https://github.com/driverdan/node-XMLHttpRequest 的内容 Node 中没有 XMLHttpRequest
。 XMLHttpRequest
是一个仅存在于浏览器中的对象。
您必须要求 http 才能在 Node 中发出 http 请求。
var http = require('http');
然后你可以做类似的事情( taken from the docs ):
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.')
})
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end(
);
关于javascript - 为什么我不能在我的亚马逊服务器上使用新的 XMLHttpRequest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37609064/