Using Node.js to connect to a REST API

2019-01-22 05:16发布

问题:

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 a hosted eCommerce platform

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

回答1:

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.



回答2:

Sure. The node.js API contains methods to make HTTP requests:

  • http.request
  • http.get

I assume the app you're writing is a web app. You might want to use a framework like Express to remove some of the grunt work (see also this question on node.js web frameworks).



回答3:

A more easy and useful tool is just using an API like Unirest; URest is a package in NPM that is just too easy to use jus like

 app.get('/any-route', function(req, res){
     unirest.get("https://rest.url.to.consume/param1/paramN")
       .header("Any-Key", "XXXXXXXXXXXXXXXXXX")
       .header("Accept", "text/plain")
       .end(function (result) {
       res.render('name-of-the-page-according-to-your-engine', {
         layout: 'some-layout-if-you-want',
         markup:  result.body.any-property,
    });

});