简体   繁体   中英

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. The third party requires a ID and key to be passed over. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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