1

I have my api with my backend: https://pure-reaches-69883.herokuapp.com/api/wallet-info

When I call this api using Postman or my browser it's working, but I have tried to call it in my browser using Axios so as to display the data but it's not working.

This is the code:

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;

halfer
  • 19,824
  • 17
  • 99
  • 186
  • Do you see any errors in your console? – zero298 Apr 15 '21 at 20:50
  • yes another error saying smthn like cor headers whatever – Jimu Collins Apr 15 '21 at 20:56
  • @rayhatfield i aint sure let me try – Jimu Collins Apr 15 '21 at 20:56
  • I tried. There is CORS error: `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)` – Ajeet Shah Apr 15 '21 at 20:58
  • @AjeetShah eish hectic so what causes the Cross-Origin Request to be blocked – Jimu Collins Apr 15 '21 at 21:00
  • If you want to understand, see [this question](https://stackoverflow.com/q/19743396/2873538). To get rid of this error, you need to set Response Headers at backend such that it allows [e.g. all the required Origins and Methods](https://stackoverflow.com/a/66413299/2873538). If you are using *nodejs / expressjs*, see [this](https://stackoverflow.com/a/45049763/2873538). – Ajeet Shah Apr 15 '21 at 21:02
  • 1
    i am grateful let me try that @AjeetShah – Jimu Collins Apr 15 '21 at 21:07
  • You can read [How does Access-Control-Allow-Origin header work?](https://stackoverflow.com/q/10636611/2873538) as well. – Ajeet Shah Apr 15 '21 at 21:09
  • @AjeetShah ok thank you let me read – Jimu Collins Apr 15 '21 at 21:12

1 Answers1

-1

You can try to do this

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 });
 })
}

Apply an await to axios to wait for the data to finish arriving.