【问题标题】:How to render the results of an http request in Express?如何在 Express 中呈现 http 请求的结果?
【发布时间】:2013-04-30 21:04:16
【问题描述】:

使用 Request 和 Express,我如何访问我的 http 请求的结果以进行渲染?

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 });
    }
  });
};

事实上,我在请求回调中引用的 res 是原始响应对象,我想知道如何从我的exports.index 函数调用响应而不使请求无法访问。

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    只需重命名参数之一:

    // 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 });
      }
    };
    

    【讨论】:

    • 这会抛出“对象不是函数”的错误。但是,通过将我的请求包装在 res.render 中,而不是相反,我让它按预期工作。
    猜你喜欢
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多