node.js - 从 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();
});
解决方案
响应负载如下所示:
{"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];
推荐阅读
- javascript - 动态加载 JS 库时出现“未定义”错误
- javascript - 错误 TS2339:“HTMLElement”类型上不存在属性“名称”
- xtext - 在 Xtext Validator 中引用语法
- delphi - 在 Windows 10 中支持高 DPI UI
- ios - ios TableviewCell重新计算高度
- asp.net-core - 最新版本的 SignalR(版本 2.4.0)可以与 MVC 5 一起使用吗?
- spring-boot - Spring Boot 2.0.5 升级到 2.1.1 在启动 Jcache 问题时失败
- cudnn - 状态为 execution_failed 的 cudnn RNN 实现
- java - 在 OpenCV 3.2 中返回 Java 中的 Mat 对象
- android - JSON 返回不可读的数据;如何获得正确的对象?(科特林,Android 工作室)