简体   繁体   中英

Node.js - pass variable between sessions

Say I have this code in node.js:

app.post('/stuff', function(req, res){
  res.send('hello world');
});
app.route('*').all(function(req,res,next){
  res.write('Hello World');
});

There are 2 routes here - one is a catch-all for any request to the server and the other is what to do if a post request with a route of /stuff is sent.

Is it possible to pass a value local to the post request into route?

Intended Program flow: initial request to the server goes through route (which has controls not illustrated to ignore post requests) and the connection is left open, then a post request is sent from the initial request and is dealt with by app.post - can a value found within the closure of post be passed to the initial request that is still open?

I am trying to avoid using Global variables, and res.local only has a local scope. Also trying to keep clean so if I can use native express or node.js all the better. Much obliged for any help.

then a post request is sent from the initial request

Why don't you simply pull out the POST function and call it from both handlers, that way you don't need to send a seperate request from inside your app.

var postHandler = function(req, res) {
   res.send('hello world');

   // Just return whatever you want back to the calling function
   return someValue; 
};

// Set it as the handler for post.
app.post('/stuff', postHandler); 

app.route('*').all(function(req,res,next){

  // Call function.
  var returnValue = postHandler(req, res);
  res.write('Hello World');
});
app.route('*').all(function(req,res,next){
  if (req.originalUrl === '/stuff') {
    req.variable = 'some value';
    return next();
  };
  res.write('Hello World');
});


app.post('/stuff', function(req, res){
  var value = req.variable;
  res.send('hello world');
});

You can try this code. Please take the order of app.all and app.post .

The second way, your can try app.locals http://www.expressjs.com.cn/4x/api.html#app.locals

The app.locals object is a JavaScript object, and its properties are local variables within the application.

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