【问题标题】:Using Node.js to connect to a REST API使用 Node.js 连接到 REST API
【发布时间】:2013-04-22 13:31:03
【问题描述】:

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

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

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

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

【问题讨论】:

  • 是的,没关系。我不明白为什么你不能为此目的使用 node.js。

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


【解决方案1】:

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

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

【讨论】:

  • 我真的很喜欢节点事件模型。当数据像这样分块时。是否可以在流结束之前开始操作它?它按顺序到达吗?
  • 谢谢!是的,数据按顺序流式传输。如果您能够在流式传输完成之前使用数据,我不明白为什么您不能在那之前使用它(尽管我个人还没有使用它的用例)。
【解决方案2】:

当然。 node.js API 包含发出 HTTP 请求的方法:

我假设您正在编写的应用程序是一个网络应用程序。您可能希望使用像 Express 这样的框架来消除一些繁重的工作(另请参阅 this question on node.js web frameworks)。

【讨论】:

    【解决方案3】:
    /*Below logics covered in below sample GET API    
        -DB connection created in class
        -common function to execute the query 
        -logging through bunyan library*/
    
    
    const { APIResponse} = require('./../commonFun/utils');
        const createlog = require('./../lib/createlog');
        var obj = new DB();
        //Test API
        routes.get('/testapi', (req, res) => {
            res.status(201).json({ message: 'API microservices test' });
        });
        dbObj = new DB();
        routes.get('/getStore', (req, res) => {
            try {
                //create DB instance
    
                const store_id = req.body.storeID;
                const promiseReturnwithResult = selectQueryData('tablename', whereField, dbObj.conn);
                (promiseReturnwithResult).then((result) => {
                    APIResponse(200, 'Data fetched successfully', result).then((result) => {
                        res.send(result);
                    });
                }).catch((err) => { console.log(err); throw err; })
            } catch (err) {
                console.log('Exception caught in getuser API', err);
                const e = new Error();
                if (err.errors && err.errors.length > 0) {
                    e.Error = 'Exception caught in getuser API';
                    e.message = err.errors[0].message;
                    e.code = 500;
                    res.status(404).send(APIResponse(e.code, e.message, e.Error));
                    createlog.writeErrorInLog(err);
                }
            }
        });
    
        //create connection
        "use strict"
        const mysql = require("mysql");
    
        class DB {
          constructor() {
            this.conn = mysql.createConnection({
              host: 'localhost',
              user: 'root',
              password: 'pass',
              database: 'db_name'
            });
          }
    
          connect() {
            this.conn.connect(function (err) {
              if (err) {
                console.error("error connecting: " + err.stack);
                return;
              }
              console.log("connected to DBB");
            });
          }
          //End class
        }
    
        module.exports = DB
    
    
        //queryTransaction.js File
    
        selectQueryData= (table,where,db_conn)=>{  
            return new Promise(function(resolve,reject){
              try{  
                  db_conn.query(`SELECT * FROM ${table} WHERE id = ${where}`,function(err,result){
                    if(err){
                      reject(err);
                    }else{
                      resolve(result);
                    }
                });
              }catch(err){
                  console.log(err);
              }
            });
        }
    
        module.exports= {selectQueryData};
    
        //utils.js file
    
        APIResponse = async (status, msg, data = '',error=null) => {  
          try {
            if (status) {
              return { statusCode: status, message: msg, PayLoad: data,error:error }
            }
          } catch (err) {
            console.log('Exception caught in getuser API', err);
          }
        }
    
        module.exports={
          logsSetting: {
            name: "USER-API",
            streams: [
                {
                    level: 'error',
                    path: '' // log ERROR and above to a file
                }
            ],
          },APIResponse
        }
    
        //createlogs.js File
    
        var bunyan = require('bunyan');
        const dateFormat = require('dateformat');
        const {logsSetting} = require('./../commonFun/utils');
    
        module.exports.writeErrorInLog = (customError) => {
          let logConfig = {...logsSetting};
          console.log('reached in writeErrorInLog',customError)
          const currentDate = dateFormat(new Date(), 'yyyy-mm-dd');
          const path = logConfig.streams[0].path = `${__dirname}/../log/${currentDate}error.log`;
          const log = bunyan.createLogger(logConfig);
          log.error(customError);
    
        }
    

    【讨论】:

      【解决方案4】:

      一个更简单有用的工具就是使用像 Unirest 这样的 API; URest 是 NPM 中的一个包,使用起来简直太容易了

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

      });

      【讨论】:

      • "res" 未定义!
      • 你一定要把它放到app.get('/', auth.protected, function (req, res){ });的路由中
      猜你喜欢
      • 1970-01-01
      • 2019-06-10
      • 1970-01-01
      • 2014-12-24
      • 2019-06-10
      • 2020-06-19
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      相关资源
      最近更新 更多