使用 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/