使用Node.js连接到REST API

使用Node.js写一个连接两个REST API的独立应用程序是否明智?

一端是POS销售点系统

另一个将是一个托pipe的电子商务平台

将有一个最小的界面来configuration服务。 而已。

是的,Node.js非常适合调用外部API。 然而,就像Node中的所有东西一样,这些调用的function是基于事件的,这意味着做缓冲响应数据而不是接收单个完成的响应。

例如:

// get walking directions from central park to the empire state building var http = require("http"); url = "http://maps.googleapis.com/maps/api/directions/json?origin=Central Park&destination=Empire State Building&sensor=false&mode=walking"; // get is a simple wrapper for request() // which sets the http method to GET var request = http.get(url, function (response) { // data is streamed in chunks from the server // so we have to handle the "data" event var buffer = "", data, route; response.on("data", function (chunk) { buffer += chunk; }); response.on("end", function (err) { // finished transferring data // dump the raw data console.log(buffer); console.log("\n"); data = JSON.parse(buffer); route = data.routes[0]; // extract the distance and time console.log("Walking Distance: " + route.legs[0].distance.text); console.log("Time: " + route.legs[0].duration.text); }); }); 

如果你打算进行大量的这些调用,那么find一个简单的包装库(或者自己写)是有意义的。

当然。 node.js API包含用于发出HTTP请求的方法:

  • http.request
  • http.get

我假设你正在编写的应用程序是一个Web应用程序。 您可能希望使用像Express这样的框架来删除一些烦人的工作(另请参阅node.js Web框架上的这个问题 )。

一个更简单有用的工具就是使用像Unirest这样的API; UREST是NPM中的一个包,它很容易使用

  app.get('/any-route', function(req, res){ unirest.get("https://rest.url.to.consume/param1/paramN") .header("Any-Key", "XXXXXXXXXXXXXXXXXX") .header("Accept", "text/plain") .end(function (result) { res.render('name-of-the-page-according-to-your-engine', { layout: 'some-layout-if-you-want', markup: result.body.any-property, }); 

});