使用Node.js连接到REST API [英] Using Node.js to connect to a REST API

查看:175
本文介绍了使用Node.js连接到REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it sensible to use Node.js to write a stand alone app that will connect two REST API's?

一端是POS - 销售点 - 系统

One end will be a POS - Point of sale - system

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

The other will be a hosted eCommerce platform

将有一个用于配置服务的最小接口。没有更多。

There will be a minimal interface for configuration of the service. nothing more.

推荐答案

是的,Node.js非常适合调用外部API。然而,就像Node中的所有内容一样,进行这些调用的函数都是基于事件,这意味着执行缓冲响应数据而不是接收单个完成的响应。

Yes, Node.js is perfectly suited to making calls to external APIs. Just like everything in Node, however, the functions for making these calls are based around events, which means doing things like buffering response data as opposed to receiving a single completed response.

例如:

// 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);
    }); 
}); 

如果你打算找到一个简单的包装库(或自己编写)可能是有意义的做了很多这些电话。

It may make sense to find a simple wrapper library (or write your own) if you are going to be making a lot of these calls.

这篇关于使用Node.js连接到REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆