2013-04-22 94 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