0

I'm new to React and I'm trying to use it to fetch data from a publicly available endpoint that exposes a simple JSON object. I can see the data by hitting this endpoint via my browser, via Postman, etc. But React keeps returning "Type Error: failed to fetch". What am I doing wrong?

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import "./styles.css";

function App() {
  const [data, setData] = useState({});

  useEffect(() => {
    (async () => {
      const response = await fetch(
        "https://phmwu2mdn6.execute-api.eu-central-1.amazonaws.com/dev/conferences/GetDigital2023/Lectures"
      );
      const parsed = await response.json();
      setData(parsed);
    })();
  }, []);

  return (
    <div>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

I need to see the JSON data, not the error message.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
PJK
  • 5
  • 1

1 Answers1

-2

The error you're encountering indicates a Cross-Origin Resource Sharing (CORS) policy issue. This problem occurs when you try to make an AJAX request (using the fetch function in your case) from a different origin than the server.

In your code, you're making a fetch request to the URL https://phmwu2mdn6.execute-api.eu-central-1.amazonaws.com/dev/conferences/GetDigital2023/Lectures from the origin http://localhost:3000. However, the server is not returning the required Access-Control-Allow-Origin header to allow requests from that origin.

To resolve this issue, you can try the following solutions:

  1. Contact the API owner or the server developer and ask them to add the Access-Control-Allow-Origin: * header to the response. This will allow requests from any origin.

  2. If you have control over the server, you can configure it to add the Access-Control-Allow-Origin header to the response. The way to do this depends on the server you're using. For example, if you're using Node.js with Express, you can use the cors middleware to handle CORS permissions.

  3. If you're unable to modify the server, you can try using a proxy to bypass the CORS policy restrictions during development. You can set up a local proxy server that redirects requests from your application to the remote API. This makes all requests appear as if they are being made from the same origin, thus avoiding CORS problems.

To use a proxy in your React application, you can use a package called http-proxy-middleware. Follow these steps to set up a proxy in your application:

  1. Install the http-proxy-middleware package using npm or yarn:
npm install http-proxy-middleware

or

yarn add http-proxy-middleware
  1. In your project folder, create a file called setupProxy.js (the exact name is important) next to the package.json file.

  2. In setupProxy.js, you can configure the proxy to redirect requests to the remote API. For example, if you want to redirect all requests starting with /api to https://phmwu2mdn6.execute-api.eu-central-1.amazonaws.com, you can use the following code:

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'https://phmwu2mdn6.execute-api.eu-central-1.amazonaws.com',
      changeOrigin: true,
    })
  );
};
  1. Make sure your React application is running in development mode (npm start or yarn start). When you run the application, the proxy will be set up, and requests to /api will be redirected to the remote API.

Now, in your React code, you can make requests using the relative URL /api. For example:

(async () => {
      const response = await fetch(
        "/api/dev/conferences/GetDigital2023/Lectures"
      );
      const parsed = await response.json();
      setData(parsed);
 })();

With this proxy configuration, all requests starting with /api will be redirected to https://phmwu2mdn6.execute-api.eu-central-1.amazonaws.com. Make sure to replace https://phmwu2mdn6.execute-api.eu-central-1.amazonaws.com with the actual URL of your remote API.

This approach helps bypass CORS issues during development, but remember to consider CORS restrictions when deploying your application in production.

tnougosso
  • 72
  • 1
  • 4
  • 1
    Welcome back to Stack Overflow, Darlinho. It looks like it's been a while since you've posted and may not be aware of the latest policies since your answer appears likely to have been entirely or partially written by AI (e.g., ChatGPT). As a heads-up, [posting of AI-generated content is not permitted on Stack Overflow](//meta.stackoverflow.com/q/421831). If you used an AI tool to assist with any answer, I would encourage you to delete it. Thanks! – NotTheDr01ds Jul 17 '23 at 23:25
  • 2
    **Readers should review this answer carefully and critically, as AI-generated information often contains fundamental errors and misinformation.** If you observe quality issues and/or have reason to believe that this answer was generated by AI, please leave feedback accordingly. – NotTheDr01ds Jul 17 '23 at 23:25
  • 1
    This answer looks like it was generated by an AI (like ChatGPT), not by an actual human being. You should be aware that [posting AI-generated output is officially **BANNED** on Stack Overflow](https://meta.stackoverflow.com/q/421831). If this answer was indeed generated by an AI, then I strongly suggest you delete it before you get yourself into even bigger trouble: **WE TAKE PLAGIARISM SERIOUSLY HERE.** Please read: [Why posting GPT and ChatGPT generated answers is not currently allowed](https://stackoverflow.com/help/gpt-policy). – tchrist Jul 18 '23 at 18:29