Reputation: 51
I tried to fetch api by using express. However, I dont know why app.get cannot get any result. In browser, I have to so long...still have not get any result.
However, i run the api link on postman, it works fine to me. Do I miss everything??
import * as express from 'express'
import {Request, Response} from 'express'
import * as bodyParser from 'body-parser'
import * as path from 'path';
import fetch from 'node-fetch';
const app = express();
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
const PORT = 8080
app.listen(PORT, ()=>{
console.log('listening to PORT 8080 ')
})
app.get('/', async function(req:Request,res:Response){
try{
await getResidentialData()
}catch(e){
console.log("error")
}
})
async function getResidentialData(){
const res = await fetch('https://api.coinbase.com/v2/currencies')
const result = await res.text();
return result
}
Upvotes: 1
Views: 193
Reputation: 1548
I feel app.get
is not returning anything since it doesn't send any response
back. To send a response back, its always best to use res
object in your API call like so:
app.get('/', async function(req:Request,res:Response){
try{
const result = await getResidentialData()
res.status(200).send(result) //<----- add this
}catch(e){
console.log("error")
res.status(400).send("Something went wrong") //<----- add this
}
})
Upvotes: 2