How to Pass Data Between Routes in Express

19,118

You can use

app.post('/getData', function(req, res){
  app.set('data', req.body.exampleVariable);
});
app.get('/displayData', function(req, res) {
  res.render('/examplePage.ejs', {retrievedData : app.get('data')});
});

but there is no guarantee that the returned data will be the data that the user set, and the data won't be sent until a user makes a request to get route. This is also making your express server stateful, which comes with a lot of possible disadvantages.

You can read a bit about it here

If you want your app to be stateless, you can instead pass your to somewhere external, like a remote server like mysql which is independant of the express server.

In case it is of any use, you can also send and receive data in the same request if you prefer, as in your comment this seems to be what you are trying to do. If you have something like below, it should be working fine, as long as you are definitely making a "POST" request to "/data", considering it was working fine for "GET" requests.

app.post('/data', function(req, res){
  res.render('/examplePage.ejs', {
    retrievedData: req.body.exampleVariable
  });
});

Below is an example express app to show how this might work

form.jade

form(method="post" action="data")
  input(type="text" name="data" value="some data")
  input(type="submit" value="submit")

data.jade

h1=data

server.js

require('express')()
  .use(require('body-parser').urlencoded({ extended: false }))
  .get('/form', (req, res) => res.render('form.jade'))
  .post('/data', (req, res) => res.render('data.jade', { data: req.body.data }))
  .listen(8083);

If you start the server and go to "localhost:8083/form", after submitting the form you are shown a rendered page containing the data that you posted.

Share:
19,118
Perturbative
Author by

Perturbative

Updated on June 17, 2022

Comments

  • Perturbative
    Perturbative almost 2 years

    Suppose I have this POST route which receives some data.

    app.post('/getData', function(req, res){
      var retrievedData = req.body.exampleVariable;
       // Send data to GET method
    });
    

    And I have this GET method which renders a page, but needs the data I retrieved in the POST method

    app.get('/displayData', function(req, res){
      // Retrieve data from POST method and display it.
      res.render('/examplePage.ejs', {retrievedData : req.retrievedData});
    });
    

    What is the best way to pass the retrievedData variable from the given POST route to the GET route?

    As a side note, the res.render() method only seems to work in app.get() type methods