简体   繁体   中英

how to return a value from express middleware as a separate module

I have put the server setting script into a separate js file called server.js . My problem is that I don't know how to get the value of cookie_key from the express middleware function and pass it back to the index.js file.

server.js :

var express = require('express'), 
app = express(), 
http = require('http').createServer(app),
cookie = cookieParser = require('cookie-parser'),
url = require('url');

module.exports = {

 use_app : function(){
  app.use(function (req, res, next) {
  var cacheTime = 86400000*7; // 7 days
  if (!res.getHeader('Cache-Control')) 
   res.setHeader('Cache-Control', 'public, max-age=' + (cacheTime / 1000));
   next();
  }); 
 },

 get_app : function(callback){
  app.use(cookieParser());
  app.get('/id/:tagId', function(req, res){ // parse the url parameter to get the file name
   function getkey(err,data){ // get users' session cookie
    var cookie_key;
    if(err)
    {
      callback(err);
    }
    cookie_key = req.cookies["session"];
    callback(cookie_key);
   }
   var filename = req.param("tagId");
   res.sendFile(filename+'.html');
  });
 }

}

index.js :

var server = require('./server'),
server.use_app();
server.get_app(); // how to get the cookie_key when calling this function?
console.log(show_cookie_key_from the module); 
if(cookie_key !== undefined)
{
   // do something
}

I tried to write a callback function to fetch the cookie key but I don't think it's working.

Update from AB's answer:

var server = require('./server');
server.use_app();
server.get_app(function(cookie){
  if(cookie !== undefined)
  {
    // do something
  }
}); 

But I still think there is something strange about this setup, what exactly are you trying to accomplish with splitting the app up like this?

Since you are using callback function and that is being poplulated with cookie value , you can get this like following:

var server = require('./server');
server.use_app();
 server.get_app(function(cookie){
cookie_key= cookie
if(cookie_key !== undefined)
{
   // do something
}
}); 

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