是的,Node.js非常适合于调用外部API。就像Node中的所有内容一样,进行这些调用的功能都是基于事件的,这意味着要做一些事情,例如缓冲响应数据,而不是接收单个完整的响应。
例如:
// get walking directions from central park to the empire state buildingvar 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 GETvar 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); }); });如果要进行很多此类调用,找到一个简单的包装库(或编写自己的包装库)可能很有意义。



