I've been learning about working with APIs and have been developing a web application to convert cryptocurrencies to fiat currencies. I've been trying to parse the JSON from the API call, but I keep getting the following error saying that the body is undefined.
SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at Request._callback (C:\Users\cfarrell\Desktop\Bitcoin-Ticker\index.js:33:21)
at self.callback (C:\Users\cfarrell\Desktop\Bitcoin-Ticker\node_modules\request\request.js:185:22)
at Request.emit (events.js:223:5)
at Request.onRequestError (C:\Users\cfarrell\Desktop\Bitcoin-Ticker\node_modules\request\request.js:881:8)
at ClientRequest.emit (events.js:223:5)
at TLSSocket.socketErrorListener (_http_client.js:406:9)
at TLSSocket.emit (events.js:223:5)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
I've checked the URL for the API manually (https://apiv2.bitcoinaverage.com/convert/global?from=BTC&to=USD&amount=5) and it has data. I haven't found any typos or anything, so I don't know what I've done wrong. I've tried reading some of the other answers for this type of error, but nothing seems to be working, and I don't understand what to do.
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res) {
var crypto = req.body.crypto;
var fiat = req.body.fiat;
var amount = req.body.amount;
var options = {
url: "https://apiv2.bitcoinaverage.com/convert/global",
method: "GET",
qs: {
from: crypto,
to: fiat,
amount: amount,
}
};
request(options, function(error, response, body) {
var data = JSON.parse(body);
var price = data.price;
var currentDate = data.time;
res.write("<p>The current date is " + currentDate + "</p>");
res.write("<h1>The current price of " + amount + " " + crypto +
" is currently worth " + price + " " + fiat + "</h1>");
res.send();
})
});
app.listen(3000, function() {
console.log("Server is running on port 3000.");
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Bitcoin Ticker</title>
</head>
<body>
<h1>Bitcoin Ticker</h1>
<form action="/" method="post">
<input type="text" name="amount" placeholder="Quantity">
<select name="crypto">
<option value="BTC">Bitcoin</option>
<option value="ETH">Ethereum</option>
<option value="LTC">Litecoin</option>
</select>
<select name="fiat">
<option value="USD">US Dollars</option>
<option value="GBP">GB Pounds</option>
<option value="EUR">EU Euros</option>
</select>
<button type="submit" name="button">Check</button>
</form>
</body>
</html>