https://codepen.io/kurtisgrant/pen/YzpJZMp

Tell us what’s happening:

This project was working correctly when I made it a couple weeks ago, but now I can’t seem to get my GET request with axios working. I’m getting a network error now when I try to send requests. I don’t think I created a bug that broke the app but I’m not entirely sure.

Your code so far
My React Component:


class QuoteBox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.newQuote = this.newQuote.bind(this);
    this.newQuoteHandler = this.newQuoteHandler.bind(this);
    this.newQuote();
  }
  
  
  newQuote() {
    axios.default.get('https://zenquotes.io/api/random')
      .then(res => {
        const quote = res[0];
        this.setState({
          quote: quote.q,
          author: quote.a
        })
      }).catch(function (error) {
        console.log(error);
      })
  }
  newQuoteHandler(event) {
    event.preventDefault();
    this.newQuote();
  }
  render() {
    return (
      <div id='quote-box'>
        <QuoteText quote={this.state.quote}/>
        <QuoteAuthor author={this.state.author}/>
        <div id='interactive-row'>
          <TweetQuoteBtn quote={{ text: this.state.quote, author: this.state.author }}/>
          <NewQuoteBtn newQuoteHandler={this.newQuoteHandler}/>
        </div>
      </div>
    )
  }
}

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.16; rv:85.0) Gecko/20100101 Firefox/85.0.

Challenge: Build a Random Quote Machine

Link to the challenge:

OK, so the error you are getting is a CORS error. From the console:

Access to XMLHttpRequest at ‘https://zenquotes.io/api/random’ from origin ‘https://cdpn.io’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

CORS is a pain in the butt, and rather than deal with that, a quick and dirty solution would be to use a CORS proxy:

      url: 'https://cors-anywhere.herokuapp.com/https://zenquotes.io/api/random',

You would never want to do that for a production app, but for something like this, it is fine. You can research CORS on your own.

And then the data is the wrong shape, so I needed:

const quote = res.data[0];

When I fix those, the app works.

1 Like

Yes, perfect this did work! Thank you!

For anyone who comes across this, I think these proxies are sometimes tied up with too many requests. At first I thought this solution wasn’t working but it was just that the proxy was bogged down. I was getting “429 - Too many requests” errors and also had to add in the header “Retry-After: 3600” which makes your app veeery slow but at least allows it to eventually get a successful request in. (That was my understanding at least) Later in the day, this solution worked perfectly without issues and didn’t need the retry-after header.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.