gpt4 book ai didi

reactjs - react /Axios : fetch API data with key for CoinMarketCap

转载 作者:行者123 更新时间:2023-12-02 19:35:39 24 4
gpt4 key购买 nike

这里没有编程经验...我一直在阅读一些与此相关的问题,但无法正确解决。我将 React 用于一个小型应用程序,并希望从 API(本例中为 Coinmarketcap)获取数据,但它需要一个 key ,并且不知道如何通过 axios 传递它。使用 Postman 发出测试请求,工作正常。

这是 API 接收请求的方式(Node.js 示例):

const rp = require('request-promise');
const requestOptions = {
method: 'GET',
uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
qs: {
'start': '1',
'limit': '5000',
'convert': 'USD'
},
headers: {
'X-CMC_PRO_API_KEY': 'b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c'
},
json: true,
gzip: true
};

rp(requestOptions).then(response => {
console.log('API call response:', response);
}).catch((err) => {
console.log('API call error:', err.message);
});

这是我的 React 文件的代码:

import React, { Component } from 'react'
import axios from 'axios'

class Prices extends Component {

state = {
cryptos: []
}

componenDidMount() {

axios.get('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest', {
headers: { 'X-CMC_PRO_API_KEY': 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' }
})
.then(res => {
console.log(res)
this.setState({
cryptos: res.data.slice(0,50)
})
});
}
render() {
return(
<div>asdf</div>
)
}
}

export default Prices

显然,我把 key 藏在那里了。

  1. 应用运行正常
  2. 没有明显错误,但也...
  3. 没有登录控制台

问题不在于我是否做错了什么,而在于……

提前感谢您对我的帮助。

编辑:父文件代码

import Layout from '../components/Layout'
import Prices from '../components/prices'
import axios from 'axios'

const Index = (props) => (
<Layout>
<div className="container">
<h1>Welcome to CoinInfo</h1>
<p>Check current Bitcoin rates</p>
<Prices />
</div>
</Layout>
)

export default Index

最佳答案

您的请求中缺少查询字符串参数,并且存在拼写错误。它是 componentDidMount,组件中缺少 t

请尝试以下代码。

import React, { Component } from 'react'
import axios from 'axios'
class Prices extends Component {
state = {
cryptos: []
}

componentDidMount() {
this.fetchData();
}

async fetchData() {
let qs = `?start=1&limit=5000&convert=USD`
try {
let res = await axios.get('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest' + qs, {
headers: { 'X-CMC_PRO_API_KEY': 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' }
});
console.log(res)
this.setState({
cryptos: res.data.slice(0, 50)
});
} catch (error) {
console.log(error);
}

}
render() {
return (
<div>asdf</div>
)
}
}
export default Prices

关于reactjs - react /Axios : fetch API data with key for CoinMarketCap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61072579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com