0

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>
C Farrell
  • 25
  • 6
  • Verify using your browser dev tools, that this is indeed requesting the exact URL you think it does. – 04FS Jan 20 '20 at 11:34
  • check data type of the body variable . – dhamo Jan 20 '20 at 12:26
  • Does this answer your question? [Uncaught SyntaxError: Unexpected token u in JSON at position 0](https://stackoverflow.com/questions/46613243/uncaught-syntaxerror-unexpected-token-u-in-json-at-position-0) – PLASMA chicken Jan 20 '20 at 12:51
  • Nothing seems to be wrong with the url. I've even hardcoded the url once as a test and it still gives the same error. The body variable always seems to be undefined but I don't know why. Also I looked at the article but it doesn't seem to help me figure out how to solve my problem. – C Farrell Jan 21 '20 at 16:47
  • To clarify, yes it does give me reasons why I'm getting that error and I know it's related to the data I'm getting from the client. The problem is that in dev tools, I can see that the POST method is being called in developer tools but it doesn't mention the GET method from the options parameter. I don't know if I just wouldn't get to see that method in my logs as it's run as parameter or if I should expect it. – C Farrell Jan 22 '20 at 09:21

1 Answers1

0

You are getting data as an array, not an object. Inside data, it is at the 0th index. You check inside data[0] and not inside data. So the answer will be data[0].image

app.post("/", function(req, res){
    request("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=10&page=1&sparkline=false" , function(error, response, body){
        var data = JSON.parse(body);
        var price = data[0].current_price;
        res.send("<h1> The bitcoin price is " + price + " USD</h1>");
    });
});
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103