【问题标题】:Why can I not use new XMLHttpRequest on my amazon server?为什么我不能在我的亚马逊服务器上使用新的 XMLHttpRequest?
【发布时间】:2016-06-03 16:14:26
【问题描述】:

所以请多多包涵,因为我觉得我已经尝试了所有可以尝试的方法。我对 JavaScript 真的很陌生,而且我以前主要使用 C/C++,而且对于这些语言我仍然是新手。我试图在我的 aws 服务 (ec2) 服务器上创建一个页面,当使用 URL 的 get 请求访问该页面时,它将使用我的服务器端 API 密钥并返回它从给定 URL 请求的 JSON 数据。我正在使用英雄联盟 API 和 NodeJs,使用永远启动 *.js、把手和表达 JavaScript。

我觉得有必要提一下,虽然这个问题是在为一门课程做作业时出现的,但我已经完成了作业,但没有包含该功能。

我尝试以同步和异步的方式执行此操作,但它对我不起作用。我觉得这是因为使用 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"

})

感谢您的帮助和您的时间。

【问题讨论】:

  • 如果你想保持你的代码完整,node 有 ajax polyfills,否则从浏览器 JS 转换为 nodeJS

标签: javascript node.js amazon-web-services amazon-ec2


【解决方案1】:

除非您使用 https://github.com/driverdan/node-XMLHttpRequest 之类的东西,否则节点中没有 XMLHttpRequestXMLHttpRequest 是一个只存在于浏览器中的对象。

您必须要求 http 才能在节点中发出 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(

);

【讨论】:

    猜你喜欢
    • 2015-12-01
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 2014-06-09
    • 2014-03-12
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多