当我进行取回请求时,我得到了一个500错误,但当我只是返回一个数组值时,一切都很顺利,请告诉我
My server.js文件:
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');
});
我的取回请求:
export default class CoinsService {
static async getAll(page ) {
let response: ICoin[] = []
await axios.get('/coins').then(data => console.log(data)
)
}
}
我试图输出确切的错误,但得到相同的消息:在这里输入图像描述输入图片描述
- 正如@Vahid Alimohamadi评论中所提到的,如果你使用promise,你不需要
await
- 最有可能的错误是来自这一行:
await axios.get<ICoin[]>
这里你期望Response
类型是ICoin[]
,这可能不是,用
axios.get<any>
如果错误消失,说明你已经明白了原因。
但这只是为了调试,记住:
不建议使用
any
类型
这个问题是我解决的,是我的粗心。
我用
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);
})
替换这个选项,我得到了数据。
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);
})
我想知道为什么我不能使用第一个选项?