简体   繁体   English

如何在快递路线之间传递数据?

[英]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. 我正在POST路由中进行API调用,但是由于某些原因,我无法通过POST路由中的res.render传递JSON数据。 So I'm thinking about passing the JSON object to GET route so I can render it to the right client page. 因此,我正在考虑将JSON对象传递到GET路由,以便可以renderrender到正确的客户端页面。

Heres my GET and POST routes: 这是我的GETPOST路线:

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? 我无法读取bookDetails.ejs文件中的bookdata? Is there another way pass this data to the page? 还有另一种方法可以将此数据传递给页面吗?

After post, your get method will run. 发布后,您的get方法将运行。 In the get method, you are not sending any data to ejs template, so it will not detect it. 在get方法中,您没有将任何数据发送到ejs模板,因此它不会检测到它。 You should redirect in post method, it is bad idea sometimes, 您应该使用post方法重定向,有时候这是个坏主意,

On semantic, it should be a GET router to display something about the ID resource. 从语义上讲,它应该是一个GET路由器来显示有关ID资源的信息。

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: 同样,您可以定义一个中间件函数来重用fetchResource逻辑,如下所示:

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: 为GET和POST路由器重用中间件功能:

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

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

hope helpful, good luck! 希望对您有帮助,祝您好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM