简体   繁体   English

将键和ID传递给node.js模块

[英]pass over key and id to node.js module

I am using express and setting up a module to handle the requests to a third party API. 我正在使用express并设置一个模块来处理对第三方API的请求。 The third party requires a ID and key to be passed over. 第三方要求传递ID和密钥。 I would rather not hard code the key and ID in the module but allow the server to pass it over to the module simply because it will allow more flexibility in the future. 我宁愿不对模块中的密钥和ID进行硬编码,而只允许服务器将其传递给模块,因为这将在将来提供更大的灵活性。 Here is what I have 这是我所拥有的

//app.js
var express = require('express');
var app = express();

var ghost = require('./ghost.js');
app.get('/v1/ghost.json', ghost.list_all);

//ghost.js module
exports.list_all = function (req, res) {
//THE ID AND KEY I WNAT O PASS OVER FROM app.js??????
foo.byUnique(id, key, function(error, resource) {
send_success(res, resource);
});
};


function send_success(res, data) {
//stuff
var output = {data: data };
res.end(JSON.stringify(output) + "\n");
}

// i do not want to hard code into the module the id and key as such
var id = 'myid';
var key = 'mykey';

I use a separate config file to handle all such data. 我使用一个单独的配置文件来处理所有此类数据。

// config.js
module.exports = {
 id: 'myid',
 key: 'mykey',
 something: {
    other: 'hello'
 }
};

Then in your other files just include it: 然后在其他文件中包括它:

//app.js
var express = require('express');
var app = express();
var config = require('./config.js');

...

//ghost.js module
exports.list_all = function (req, res) {
 foo.byUnique(config.id, config.key, function(error, resource) {
   send_success(res, resource);
 });
};

There are also a number of node modules that do the same in fancier ways such as handling which environment you are working with. 还有许多节点模块以更高级的方式执行相同的操作,例如处理您正在使用的环境。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM