简体   繁体   English

使用Node获取对第三方API的请求

[英]GET request to a third party API using Node

I am trying to GET some JSON data from an API and display the objects in the HTML. 我正在尝试从API获取一些JSON数据并在HTML中显示对象。 I have an index.html, server.js, and a request_json.js file. 我有一个index.html,server.js和request_json.js文件。

request_json.js request_json.js

var http = require('http');

var options = {
  host: '',
  path: ''
};

callback = function(res) {
  var str = '';

  res.on('data', function (chunk) {
    str += chunk;
  });

  res.on('end', function () {
    console.log(str);
  });
}

http.request(options, callback).end();

index.html index.html

...
<body>
  <script src="request_json.js"></script> 
</body>

So how do I insert the JSON objects that are returned into the html? 那么,如何插入返回到html中的JSON对象? When I do it this way, I receive an error: Uncaught ReferenceError: require is not defined. 当我这样做时,会出现错误:未定义的ReferenceError:require未定义。

If you want to use Node.js from a webpage then you need to: 如果要从网页上使用Node.js,则需要:

  1. Use Node.js and not just give code written to run on Node.js to a web browser. 使用Node.js ,而不仅仅是将编写在Node.js上运行的代码提供给Web浏览器。 Web browsers are not Node.js, they do not have access to Node.js's APIs. Web浏览器不是Node.js,它们无权访问Node.js的API。 In this context, Node.js is used to write server side code, not browser side. 在这种情况下,Node.js用于编写服务器端代码,而不是浏览器端代码。
  2. Create a way for Node.js and the browser to communicate. 创建Node.js与浏览器进行通信的方式。 This is typically done by writing an HTTP server in Node.js. 这通常是通过在Node.js中编写HTTP服务器来完成的。 There is a very basic example on the Node.js about page , more complicated systems tend to use Express . Node.js上有一个关于页面的非常基本的示例,更复杂的系统倾向于使用Express
  3. Express the data you want to fetch in a form that the browser can understand. 以浏览器可以理解的形式表示要获取的数据。 JSON is a popular data format, but plain HTML might be more suitable. JSON是一种流行的数据格式,但是纯HTML可能更适合。
  4. Get that data to the browser. 将该数据发送到浏览器。 Typically you would use XMLHttpRequest from JavaScript if the data is in JSON or use a link or form submission to get an HTML version. 通常,如果数据为JSON,则可以使用JavaScript的XMLHttpRequest,也可以使用链接或表单提交来获取HTML版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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