【问题标题】:How to call an API in other file in nodejs Express framework如何在 nodejs Express 框架中调用其他文件中的 API
【发布时间】:2017-02-17 21:48:39
【问题描述】:

我第一次使用 express 也是 node.js 。我正在使用 API(第三方)。我知道如何使用module.exports 将函数从一个文件调用到另一个文件。但是我怎么能调用下面格式编写的 API:

var taobao = require('taobao');
taobao.config({
    app_key: 'xxxxx',
    app_secret: 'xxxxxxxx',
    REST_URL: 'http://gw.api.taobao.com/router/rest'
});

taobao.core.call({
    "session": '620260160ZZ61473fc31270',
    "method": "taobao.wlb.imports.waybill.get",
    "format": "json",
    "tid": 21132213,
    "order_code": 'lp number',//This we have to pass.
}, function (data) {
    console.log(data);
});

我想在不同的文件中调用上述 API。我应该为此使用模块导出吗?或者有没有其他办法?

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    是的,如果你想在另一个文件中调用函数,你应该使用模块导出。

    首先,将其另存为taobao.js

    var taobao = require('taobao');
    taobao.config({
        app_key: 'xxxxx',
        app_secret: 'xxxxxxxx',
        REST_URL: 'http://gw.api.taobao.com/router/rest'
    });
    
    
    exports.taobaoCallHandler = function(callback) {
        taobao.core.call({
                "session": '620260160ZZ61473fc31270',
                "method": "taobao.wlb.imports.waybill.get",
                "format": "json",
                "tid": 21132213,
                "order_code": 'lp number',//This we have to pass.
            }, function (data) {
                console.log(data);
                return callback(data);
            });
    };
    

    在另一个文件中,你可以包含taobao.js文件并使用taobao.js中包含的函数。

    const taobao = require('./taobao');
    taobao.taobaoCallHandler(function(data) {
        //do something with the data
    });
    

    【讨论】:

      猜你喜欢
      • 2018-07-24
      • 2020-12-22
      • 2020-03-08
      • 2016-08-04
      • 2012-09-26
      • 1970-01-01
      • 2018-08-01
      • 2014-12-05
      • 1970-01-01
      相关资源
      最近更新 更多