Always_a_learner
Always_a_learner

Reputation: 5055

How to call an API in other file in nodejs Express framework

I am using express for first time and also node. I am consuming an API (third party). I know how to call a function from one file to another using module.exports. But how could I call an API written in below format:

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

I want to call the above API in a different file. Should I use module export for this? Or is there any other way?

Upvotes: 0

Views: 945

Answers (1)

Dylan Law
Dylan Law

Reputation: 327

Yes you should use module export if you want to call the function in another file.

First, save this as 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);
        });
};

And in another file, you can include taobao.js file and use the function which contains in taobao.js.

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

Upvotes: 1

Related Questions