我正在尝试使用Node.js中的请求模块,使用来自bitcoinaverage.com的API来获取比特币的当前价格。当我在localhost:3000上启动它时,我得到了页面并且HTML运行正常。我的页面有时可以工作,并且可以为我提供数据,但是大多数情况下服务器会崩溃。有时它可以工作,我不知道我的错误是什么。注意:未启用代理。
const express = require("express");
const bodyParser = require("body-parser");
const https = require("https");
const app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
});
app.post("/", function (req, res) {
request("https://apiv2.bitcoinaverage.com/indices/global/ticker/BTCUSD", function (error,
response, body) {
var data = JSON.parse(body);
var price = data.last;
var priceAverage = data.averages.week;
res.send("<h1>The price of a Bitcoin now is " + price + "</h1>");
console.log(price);
console.log(priceAverage);
console.log(response.statusCode);
});
});
控制台向我显示以下内容:
Unauthenticated requests are not allowed. Take out a new plan or start a free trial at https://pro.bitcoinaverage.com
^
SyntaxError: Unexpected token U in JSON at position 0
at JSON.parse (<anonymous>)
at Request._callback (/Users/Desktop/Web Development/Bitcoin-Ticker/index.js:60:18)
at Request.self.callback (/Users/Desktop/Web Development/Bitcoin-Ticker/node_modules/request/request.js:185:22)
at Request.emit (events.js:315:20)
at Request.<anonymous> (/Users/Web Development/Bitcoin-Ticker/node_modules/request/request.js:1154:10)
at Request.emit (events.js:315:20)
at IncomingMessage.<anonymous> (/Users/Desktop/Web Development/Bitcoin-Ticker/node_modules/request/request.js:1076:12)
at Object.onceWrapper (events.js:421:28)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1220:12)
[nodemon] app crashed - waiting for file changes before starting...