How to Pass Data Between Routes in Express

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

Suppose I have this POST route which receives some data.

2条回答
  •  旧时难觅i
    2021-01-13 18:27

    I am posting this assuming you are running express.js/node.js. All directories are in root directory.

    I think you can just use one route instead of two routes. Assuming you have the javascript function/method to get data in a directory under root directory call getModules and your method is stored in a file call getData.js.

    routes/index.js

    var getDataModule = require('../getModules/getData.js');
    
    router.post('/getData', function(req, res) {
      getDataModule.gatData(req.body, function(data) {
        res.render('/displayData', { title: 'Title', results: data });
      });
    });
    

    Then your function should be export the data. Otherwise it will not with this way. The getData.js can be like this.

    getModules/getData.js

    module.exports.getData = function(data, callback){
      //body that work on data or what ever the logic including a callback
    }
    

    Then you can render the results in displayData.ejs which is similar to normal HTML page. But if you are planning to use this diplayData.ejs as a template you can include examplePage.ejs inside the body.

    Code Explanation

    With this coding, you may send something with req.body to your function or not. But the returning value will be sent with data object. Then that is given to your next route which is going to render the data as HTML. Things that you're going to display is in results object/array. You can access to properties of the object as <%= results._source.prop1 %> and so on. But you need to know the identifier of the property.

提交回复
热议问题