簡體   English   中英

使用 Node.js 連接到 REST API

[英]Using Node.js to connect to a REST API

使用 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);
    }); 
}); 

如果您要進行大量這樣的調用,找到一個簡單的包裝庫(或編寫自己的)可能是有意義的。

當然。 node.js API 包含發出 HTTP 請求的方法:

我假設您正在編寫的應用程序是一個網絡應用程序。 您可能想要使用像Express這樣的框架來刪除一些繁重的工作(另請參閱node.js web frameworks 上的這個問題)。

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

    }

一個更簡單有用的工具就是使用像 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,
    });

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM