首页 > 解决方案 > 从 body-parser 传递参数以获取 JSON 数据的问题

问题描述

这是使用 api 和参数获取 BTC 价格的简单代码。当我尝试这段代码时,我得到了未定义,但如果我替换了“data.rates.crypto;” 通过“data.rates.BTC”我得到了当前价格的价值,尽管加密货币的价值是相同的“BTC”

app.post("/", function(req, res) {
  var crypto = req.body.crypto; //this line gives BTC
  var baseUrl = "http://api.coinlayer.com/api/live?access_key=lablabalab&symbols=";
  var finalUrl = baseUrl + crypto; //no problem here by passing the parameter whics is BTC
  request(finalUrl, function(error, response, body) {
    var data = JSON.parse(body);
    var price = data.rates.crypto;  //here is the problem
    res.write("<h1>Cuurent Price From " + crypto + " To USD is " + price + "</h1>");
    res.send();
  });

标签: node.jsjsonapi

解决方案


响应负载如下所示:

{"success":true,"terms":"https:\/\/coinlayer.com\/terms","privacy":"https:\/\/coinlayer.com\/privacy",
"timestamp":1611389888,
"target":"USD",
"rates":{"BTC":32728.891547}}

所以你需要访问data.rates,但crypto变量(BTC)的值而不是名称crypto。您可以通过哈希访问来做到这一点:

var price = data.rates[crypto];  

推荐阅读