如何在路由中呈现回调JSON响应

时间:2015-10-12 13:49:56

标签: javascript json node.js

我想将JSON响应body传递给路由index.js中的render函数

这就是我目前的情况,我无法理解这一点,以便body可以访问res.render

router.get('/', function(req, res, next) {

    var request = require('request')

    request.post('https://getpocket.com/v3/get', {
      headers: {'content-type':'application/json'},
      body: JSON.stringify({
        consumer_key:'...',
        access_token:'...',
        tag: 'nodejs'
      })
    }, function (err, res, body) {
        // how to pass body to render?
    })

    res.render('index', { 
        title: 'Express', 
        data: body
    });
}); 

1 个答案:

答案 0 :(得分:3)

你很亲密。试试这个

router.get('/', function(req, res, next) {

    var request = require('request')

    request.post('https://getpocket.com/v3/get', {
      headers: {'content-type':'application/json'},
      body: JSON.stringify({
        consumer_key:'...',
        access_token:'...',
        tag: 'nodejs'
      })
    }, function (err, response, body) {// notice i changed res to response, to differentiate between express response object and request's response
        res.render('index', { 
          title: 'Express',   
          data: body
        });
    })
});