How to Pass Data Between Routes in Express

前端 未结 2 529
夕颜
夕颜 2021-01-13 18:08

Suppose I have this POST route which receives some data.

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-13 18:30

    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.

提交回复
热议问题