如何在Express中呈现http请求的结果? [英] How to render the results of an http request in Express?

查看:51
本文介绍了如何在Express中呈现http请求的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Request和Express,如何呈现我的http请求的结果?

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

实际上,我在请求回调中引用的资源是原始响应对象,我想知道如何在不访问请求的情况下从我的exports.index函数调用响应.

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.

推荐答案

只需重命名参数之一:

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

这篇关于如何在Express中呈现http请求的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆