2013-04-22 75 views
8

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

一端将是POS - 销售点 - 系统

另将托管电子商务平台

将有服务的配置的最小接口。而已。

+0

是的,没关系。我不明白为什么你不能为此使用node.js。 – 2013-04-22 13:31:56

回答

23

是的,Node.js非常适合调用外部API。但是,就像Node中的所有内容一样,进行这些调用的函数都是基于事件的,这意味着要做缓冲响应数据而不是接收单个已完成的响应。

例如:

// 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); 
    }); 
}); 

它可能是有意义找到一个简单的包装库(或写你自己的),如果你将要作出很多这样的电话。

+0

嗯解释+1 – AndrewMcLagan 2013-04-22 23:22:53

+0

我真的很热心节点模型。当数据像这样被分块时。是否有可能在流结束之前开始操作它?它是否按顺序到达? – AndrewMcLagan 2013-04-22 23:26:56

+0

谢谢!是的,数据按顺序流式传输。如果您能够在流式传输完成之前使用这些数据,我不明白为什么您在此之前无法使用它(尽管我个人还没有使用它)。 – 2013-04-23 00:51:34

-1

一个更简单有用的工具就是使用像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, 
    }); 

});

+0

“res”未定义! – Kasra 2017-06-08 18:28:54

+0

哟必须把它放在'app.get('/',auth.protected,function(req,res){{ }});' – 2017-06-08 21:44:32

+0

的路线中,请编辑并更新代码。 – Kasra 2017-06-15 22:46:26