node.js - 使用 api 密钥使用节点快递从比特币平均值获取数据
问题描述
我正在尝试从比特币平均值中获取数据。我搜索并发现
我们所有的请求都是获取请求,它们必须包含我们的 x-ba-key 标头:
示例:'x-ba-key':'NzI0MjM4Njc1NGQ3NDU4Mzg1NWU3YYmU4MTdiMaA'
但我真的不知道在哪里以及如何在我的 .js 文件中使用。请帮我解决一下这个。这是代码
代码
//TODO 1) require express, bodyparser & request
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
//TODO 2) get the express
const app = express();
//TODO use bodyparser for getting the respnse from the local server
app.use(bodyParser.urlencoded({ extended: true }));
//TODO 3) specify the port for listening into the local server
app.listen(3000, function () {
console.log("server is running at port 3000");
});
//TODO 4) sendFile - a file to the specific route
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
});
var theBitCoinPrice;
//TODO 5) post- use body parser for getting the response from the local server.
//TODO 6) request - use request function to use the API.
app.post("/", function (req, res) {
console.log(req.body.fiat);//here we have log into the console thats why we are getting message in the console.
// res.send("Your currency is " + req.body.fiat);
var theFirstSymbol = req.body.crypto;
var theSecondSymbol = req.body.fiat;
var theAmount = req.body.amount;
var options = {
url: "https://apiv2.bitcoinaverage.com/convert/global",
method: "GET",
qs: {
from: theFirstSymbol,
to: theSecondSymbol,
amount: theAmount,
}
}
request(options, function (error, response, body) {
var data = JSON.parse(body); //here we are converting JSON object into javascript object using parse method.
var price = data.price;
var date = data.time;
console.log(date);
response.write("<h1>" + "The current date is " + date + "</h1>");
response.write("The " + theAmount + crypto + "is " + price + " " + fiat);
response.send();
});
});
解决方案
您可以在选项中添加所需的标题('x-ba-key')
var options = {
url: "https://apiv2.bitcoinaverage.com/convert/global",
method: "GET",
qs: {
from: theFirstSymbol,
to: theSecondSymbol,
amount: theAmount,
},
headers : {
'x-ba-key': 'NzI0MjM4Njc1NGQ3NDU4Mzg1NWU3YYmU4MTdiMaA'
}
}
查看请求包头文件 https://www.npmjs.com/package/request#custom-http-headers
推荐阅读
- javascript - 当php回显javascript以调用函数以更新不返回任何内容的导航菜单时,如何管理未定义?
- excel - 关闭工作簿后 Excel 函数“Application.OnTime”仍在运行
- sql - presto sql过滤部分字符串java
- r - 改变ggplot2图例中中位数和均值的颜色
- c# - 托管 Blazor Web 程序集 - Bearer error="invalid_token", error_description="未找到签名密钥"
- python - 使用 Boto3 Lambda 函数的 S3 存储桶生命周期配置并出现 MalformedXML 格式错误
- kubernetes-helm - 如何让 helm hooks 只重试一次?
- node.js - 如何在useEffect反应中停止内存泄漏
- arrays - VHDL 中的无符号加法导致不正确的长度无符号结果
- reactjs - 如何在使用 React Infinite Scroll Component 时永久显示 Y 滚动条?