首页 > 解决方案 > 使用 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();
    });

});

标签: node.jsapiexpress

解决方案


您可以在选项中添加所需的标题('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


推荐阅读