1

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?

5
  • Could you do a console.log(body) to see what are you getting from the request call? Normally payload should be the response.
    – vitomadio
    Aug 16, 2018 at 19:10
  • @VitoMadio I'm getting back the JSON object I want but I try to render in my ejs file it says its undefined. Aug 16, 2018 at 19:41
  • 1
    Well, If you are receiving a json object you don't neet to parse it, so try: let bookdata = body; instead hope it helps.
    – vitomadio
    Aug 16, 2018 at 20:12
  • @RockySingh Can you show us how you are accessing bookdata in ejs file?
    – Sridhar
    Aug 17, 2018 at 10:09
  • @SridharI resolved the issue. Thanks anyways Aug 18, 2018 at 1:10

2 Answers 2

1

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!

0

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,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.