Search code examples
reactjsfetchyahoo-api

Fetch in ReactJS works with one URL, but not another that shows same info and works in a browser


I took the URL https://query2.finance.yahoo.com/v8/finance/chart/AAPL from YFinance github for python, where it works. It also works if I put it into a browser. But I am not able to get this same URL to work in Fetch() in ReactJS. I keep getting "NetworkError when attempting to fetch resource."

Yet the code I have for Fetch() works, as it does not have a problem with the test API URL https://jsonplaceholder.typicode.com/posts as can be seen here in the working code:

import { useState, useEffect } from "react";

// Testing ways to fetch data from Yahoo Finance
// The below adapted from Fetch() method - https://blog.logrocket.com/modern-api-data-fetching-methods-react/

export default function YahooFinance() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const getData = async () => {
      try {
        const response = await fetch(
          `https://jsonplaceholder.typicode.com/posts?_limit=10`
        );
        if (!response.ok) {
          throw new Error(
            `This is an HTTP error: The status is ${response.status}`
          );
        }
        let actualData = await response.json();
        setData(actualData);
        setError(null);
      } catch(err) {
        setError(err.message);
        setData(null);
      } finally {
        setLoading(false);
      }  
    }
    getData()
  }, [])

  return (
    <div className="App">
      <h1>API Posts</h1>
      {loading && <div>A moment please...</div>}
      {error && (
        <div>{`There is a problem fetching the post data - ${error}`}</div>
      )}
      <ul>
        {data &&
          data.map(({ id, title }) => (
            <li key={id}>
              <h3>{title}</h3>
            </li>
          ))}
      </ul>
    </div>
  );
}

Solution

  • I believe the error is due to CORS. I suggest you use CORS Anywhere

    Open that webpage link above and click on the Request Access button. Then append the Yahoo URL like this inside your React App.

    https://cors-anywhere.herokuapp.com/https://query2.finance.yahoo.com/v8/finance/chart/AAPL
    

    This is only for the development environment. You don't need this on production.