简体   繁体   中英

How do I pass a variable between routes in express?

I'm trying to pass variable from one express route to another. The variable is being incremented on a POST route and I'm trying to retrieve it on the front end via a GET route.

I've tried using express-sessions but value won't increment past the first iteration of the loop.

app.post('/post-route', (req, res) => {
    // data passed from form
    let data = req.body.someArray
    let variableToPass = 0;

    // render a success/landing page
    res.render('/success',{
        title: 'page title'
        data: someData
    });
    // loop
    for(i = 0; i < data.length; i++) {
        // do something with data here
        variableToPass++;
    }
});
app.get('/get-route', (req, res) => {
    // get variable here and return to ajax request
    res.json({
      data: variableToPass
    });
});

Make it global:

let variableToPass = 0;

app.post("/post-route", (req, res) => {
  variableToPass = 0;
  // ...
});

app.get("/get-route", => {
  res.json({
    data: variableToPass
  });
});

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