【问题标题】:Express: Show value from external request as responseExpress:显示来自外部请求的值作为响应
【发布时间】:2018-01-09 16:58:17
【问题描述】:

我在使用 cryptocompare npm 包的地方有以下功能:

getPrice: function(coin){
  cc.price(coin, 'USD')
  .then(prices => {
    console.log(prices);
    return prices;
  }).catch(console.error)
}
// https://github.com/markusdanek/crypto-api/blob/master/server/helper/cryptocompare.js

现在我想设置一个 Express 服务器来打开 http://localhost:9000/current 并显示当前的“价格”。

所以我的控制器看起来像这样:

module.exports = {
    getCurrentPrice: function(req, res, next) {
      getPrice('ETH', function(price);
    }
};
// https://github.com/markusdanek/crypto-api/blob/master/server/controllers/CryptoController.jshttps://github.com/markusdanek/crypto-api/blob/master/server/controllers/CryptoController.js

我的路线:

var controllers = require('../controllers'),
    app = require('express').Router();

    module.exports = function(app) {
        app.get('/current', controllers.crypto.getCurrentPrice);
    };

当我现在打开http://localhost:9000/current 时,我只能在我的控制台中获得当前价格,而不是在我的浏览器中。

如何设置对值的响应?

我试过了,但失败了:

module.exports = {
    getCurrentPrice: function(req, res, next) {
      getPrice('ETH', function(price){
        res.status(200).json(price);
      });
    } 
};

我猜那是调用回调的错误方式。我是否必须修改我的辅助函数或其他任何东西?

我的项目也在 Github 上供进一步参考:https://github.com/markusdanek/crypto-api

【问题讨论】:

  • 再次欢迎@mrks

标签: node.js rest express callback


【解决方案1】:

以下内容可能对您有所帮助

module.exports = {
    getCurrentPrice: function(req, res, next) {
      cc.price('ETH', 'USD')
        .then(prices => {
          console.log(prices);
            res.json(prices)
        })
        .catch(err=>{
            console.error(err)
            return next(err);
        })
    }
};

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多