javascript - 使用 Node.js 连接到 REST API

标签 javascript web-services node.js rest underscore.js

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

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

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

将有一个用于配置服务的最小界面。仅此而已。

最佳答案

是的,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);
    }); 
}); 

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

关于javascript - 使用 Node.js 连接到 REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16148403/

相关文章:

java - 从另一个项目调用 spring @service

node.js - Slack 交互消息 : No POST response from Slack

javascript - Window 和 window 和有什么不一样?

Android 应用程序使用来自 Web 服务的数据

javascript - 带表格的 HTML/Javascript 弹出框

java - Web服务与java android

node.js - 替换文档不得包含原子运算符

javascript - Express 应用程序主体解析器不适用于某些 api.s

Javascript 数组为项目返回不正确的值?

javascript - V 8's "大对象空间”是否有限制?