使用Node.js连接到REST API

And*_*gan 9 javascript rest web-services node.js underscore.js

使用Node.js编写一个可以连接两个REST API的独立应用程序是否合理?

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

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

将有一个用于配置服务的最小接口.而已.

Rob*_*ell 28

是的,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);
    }); 
}); 
Run Code Online (Sandbox Code Playgroud)

如果要进行大量的这些调用,找到一个简单的包装库(或编写自己的包)可能是有意义的.