【问题标题】:How to get data as JSON from this API and display in in my Reactjs app如何从此 API 获取 JSON 格式的数据并显示在我的 Reactjs 应用程序中
【发布时间】:2021-07-10 22:09:43
【问题描述】:

我的后端有我的 api:https://pure-reaches-69883.herokuapp.com/api/wallet-info

当我使用 Postman 或我的浏览器调用此 API 时,它正在工作,但我尝试使用 Axios 在我的浏览器中调用它以显示数据,但它不工作。

这是代码:

import React, { Component } from 'react';
import './Sidebar.css';
import axios from 'axios';

class Dashboard extends Component {
  state = { walletInfo: {} };

  componentDidMount() {
    const url = 'https://pure-reaches-69883.herokuapp.com/api/wallet-info';
    axios.get(url).then(response => response.json)
 
   .then((json) => {
     
    this.setState({ walletInfo: json })
 
   })  
  }
  render() {
    const { address, balance } = this.state.walletInfo;

    return (
      <div className="ml-5 mb-5 mt-5 maincontent-area-all-pages">
        <div className="my-5 mx-4">
        <h2>Hello Page not Found</h2>
        <div className='WalletInfo'>
          <div>Address: {address}</div>
          <div>Balance: {balance}</div>
        </div>
        </div>
    </div>
    )
  }
}

export default Dashboard;

【问题讨论】:

  • 您是否在控制台中看到任何错误?
  • 是的另一个错误,说 smthn like cor headers whatever
  • @rayhatfield 我确定让我试试
  • 我试过了。出现 CORS 错误:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://pure-reaches-69883.herokuapp.com/api/wallet-info. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)
  • 我很感激让我试试@AjeetShah

标签: node.js reactjs


【解决方案1】:

你可以试试这个

async componentDidMount() {
 const url = 'https://pure-reaches-69883.herokuapp.com/api/wallet-info';
 await axios.get(url).then(response => response.json).then((json) => {
 this.setState({ walletInfo: json });
 })
}

对 axios 应用 await 以等待数据完成到达。

【讨论】:

  • @Miguel Depiante 非常感谢你让我试试
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-01
  • 2019-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多