I am creating a website using express JS using api from coingecko. At first a main.html page loads asking for crypto coin name, when we hit enter the coin details are fetched from coin gecko Api.
I have used a variable named coin to store the submitted coin from main.html page.
After I recieve a response from the api request I parse the response body which is string using JSON.parse() and store it in the obj variable.
The problem here is inside the app.post request on the line console.log(obj.coin)
when I take a coin name input and console log obj.{name of the coin I submitted} for example console.log(obj.litecoin) it gives correct response but when I try to use the coin name from the coin variable It throws error example console.log(obj.coin) throws error where coin = litecoin (as string) .
What are the possible solutions for this error ? and sorry for bad english.
the index.js file
const express = require('express')
const bodyparser = require('body-parser')
const request = require('request')
const app = express()
app.use(bodyparser.urlencoded({extended:true}))
app.use(express.static('public'))
app.set('view engine', 'ejs');
app.get("/",function(req,res){
res.sendFile(__dirname+"/public/main.html")
})
let coin = ""
let inr = ""
let usd = ""
let eur = ""
let logo = ""
let flink = "https://api.coingecko.com/api/v3/simple/price?ids="
let milink = "&vs_currencies=inr%2Cusd%2Ceur&include_market_cap=true"
app.get("/info" , function(req,res){
res.render('list' , {newcoin : coin })
})
app.post("/",function(req,res){
// console.log(req.body.coin)
coin = req.body.coin
coin = coin.toLowerCase()
request(flink+coin+milink,function(error,response,body){
let obj = JSON.parse(body)
console.log(obj.litecoin);
//console.log(obj.coin);
})
res.redirect("/info")
})
app.listen(3000, function (err) {
if (err)
console.log("Error in server setup")
console.log("Server listening on Port", 3000);
})
The main.html file
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div class="container">
<form action="/" method="post">
<div class="inp">
<input name="coin" type="text" placeholder="Enter Bitcoin">
</div>
<div class="search">
<button type="submit">Search</button>
</div>
</form>
</div>
<div class="content">
<div class="name"></div>
</div>
</body>
</html>