Rocky Singh
Rocky Singh

Reputation: 68

How to pass data between express routes?

I'm making an API call in a POST route but for some reason, I can't pass the JSON data through res.render in the POST route. So I'm thinking about passing the JSON object to GET route so I can render it to the right client page.

Heres my GET and POST routes:

router.get('/bookDetails', (req, res) => {
     res.render('bookDetails');
});

router.post('/bookDetails', (req, res) => {
     let ID = req.body.ID;
     request('https://www.googleapis.com/books/v1/volumes/' + ID, (err, response, body) => {
     if(!err && response.statusCode == 200){
       let bookdata = JSON.parse(body);
       res.render('bookDetails', {bookdata: bookdata});
    }else{
      console.log(err);
    }
  });
});

I can't read the bookdata in my bookDetails.ejs file? Is there another way pass this data to the page?

Upvotes: 1

Views: 1534

Answers (2)

XXLIVE
XXLIVE

Reputation: 156

On semantic, it should be a GET router to display something about the ID resource.

router.get('/bookDetails/:id', (req, res) => {
   let resource = await fetchResourceById
   res.render('bookDetails', resource);
});

also, you can define a middleware function to reuse the fetchResource logic, as following:

function fetchResourceMiddleware(){
  return function(req, res, next){
    var id = req.query.id || req.body.id
    if(id){
      req.resource = await fetchResource(id)
    }
    next()
  }
}

reuse the middleware function for GET and POST router:

function renderResource(req, res){
  res.render('bookDetails', req.resource);
}

router.get('/bookDetails/:id', fetchResourceMiddleware(), renderResource)
router.post('/bookDetails', fetchResourceMiddleware(), renderResource)

hope helpful, good luck!

Upvotes: 1

Nuriddin Kudratov
Nuriddin Kudratov

Reputation: 518

After post, your get method will run. In the get method, you are not sending any data to ejs template, so it will not detect it. You should redirect in post method, it is bad idea sometimes,

Upvotes: 0

Related Questions