When I make a fetch request, I get a 500 error, but when I just return an array of values, everything goes well, please tell me.
My server.js file:
const express = require('express');
const cors = require("cors");
const CoinGecko = require("coingecko-api")
const app = express();
const CoinGeckoClient = new CoinGecko();
app.use(cors())
app.get('/coins', (req, res) => {
await axios.get<ICoin[]>(`https://api.coingecko.com/api/v3/coins/markets?`, {params: {
vs_currency: "usd",
per_page: 100,
page: 1,
}})
.then((response) => {
console.log(response);
res.json(response.data);
}).catch((error) => {
console.log(error);
})
})
app.listen(5000, () => {
console.log('Server listening on port 5000');
});
My fetch request:
export default class CoinsService {
static async getAll(page ) {
let response: ICoin[] = []
await axios.get('/coins').then(data => console.log(data)
)
}
}
I tried to output the exact error but got the same message: enter image description here enter image description here
CodePudding user response:
- as montionned in @Vahid Alimohamadi comment you don't need
await
if you you are using promise - most probably the error is from this line :
await axios.get<ICoin[]>
here you are expecting the Response
type to be ICoin[]
which is probably not, replace it with
axios.get<any>
if the error disappears then you have understood the reason.
but this is only for debugging, REMEMBER:
using the
any
type is not recommanded
CodePudding user response:
I solved this problem, it was my carelessness.
I used
app.get('/coins', async (req, res) => {
CoinGeckoClient.coins.markets({
vs_currency: 'usd',
per_page: 100,
page: page,
sparkline: false
}).then((response) => {
res.json(response.data);
}).catch((error) => {
console.log(error);
})
Replacing this option, I got the data.
app.get('/coins', async (req, res) => {
await axios.get('https://api.coingecko.com/api/v3/coins/markets?', {
params: {
vs_currency: "usd", // Convert prices to USD
per_page: 100, // Get top 100 coins
page: 1, // Get first page
}
})
.then((response) => {
res.json(response.data);
}).catch((error) => {
console.log(error);
})
I would like to know why I could not use the 1st option?