0

Using Request and Express, how do I access the result of my http request for the purpose of rendering it?

var request = require('request');
var http = require('http');

exports.index = function(req, res){

  var apiUrl = 'http://api.bitcoincharts.com/v1/weighted_prices.json';

  request(apiUrl, function(err, res, data) {
    if (!err && res.statusCode == 200) {
      data = JSON.parse(data);
      console.log(data);
      res.render('index', { data: data });
    }
  });
};

As it is, the res I'm referring to within the request callback is the raw response object and I'm wondering how to call the response from my exports.index function without the request being inaccessible.

4

1 回答 1

0

Just rename one of the arguments:

// either this:
exports.index = function(req, response) {
  ...
  response.render(...);
};
// or this:
request(apiUrl, function(err, response, data) {
  if (!err && response.statusCode == 200) {
    data = JSON.parse(data);
    console.log(data);
    res.render('index', { data: data });
  }
};
于 2013-04-30T13:04:16.980 回答