Using Node.js to connect to a REST API

后端 未结 4 707
借酒劲吻你
借酒劲吻你 2020-12-13 16:15

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

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

The other will be

4条回答
  •  青春惊慌失措
    2020-12-13 16:44

    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.

    For example:

    // 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.

提交回复
热议问题