Có, Node.js hoàn toàn phù hợp để thực hiện cuộc gọi đến các API bên ngoài. Cũng giống như mọi thứ trong Node, tuy nhiên, các chức năng để thực hiện các cuộc gọi này dựa trên các sự kiện, có nghĩa là làm những việc như đệm dữ liệu phản hồi thay vì nhận được một phản hồi hoàn thành duy nhất.
Ví dụ:
// 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);
});
});
Nó có thể làm cho tinh thần để tìm thấy một thư viện wrapper đơn giản (hoặc viết riêng của bạn) nếu bạn đang đi để được làm rất nhiều các cuộc gọi.
Nguồn
2013-04-22 19:52:58
Có, không sao. Tôi không thấy lý do tại sao bạn không thể sử dụng node.js cho mục đích đó. –