2017-02-17 11 views
0

私はエクスプレスを初めて使用していますが、ノードも使用しています。私はAPI(第三者)を消費しています。 module.exportsを使ってあるファイルから別のファイルに関数を呼び出す方法を知っています。しかし、私は以下の形式で書かれたAPIを呼び出すことができます:nodejs Expressフレームワークの他のファイルで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を別のファイルで呼びたいと思います。このためにモジュールエクスポートを使用する必要がありますか?それとも他の方法がありますか?

答えて

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

ありがとうございました。私はこの解決策を試し、あなたに知らせるでしょう。どうもありがとう!!! – Simer

関連する問題