skip to Main Content

The following code is suppose to hit a node endpoint and get a response. However, nothing in the logs, both on client or server side are showing that the request was actually sent by React to node. How could I debug it?

function App() {

  /*const [data, setData] = React.useState([]);

  React.useEffect(() => {
    fetch("/")
      .then((res) => {
        console.log(`got response stringified ${JSON.stringify(res)}`);
        res.json()
      }).then((data) => {
        console.log(`data : ${data}`);
        setData(data)
      });
  }, []);
  */

  useEffect( () => {
    fetchItems();
  },[]);

  const [items,setItems] = useState([]);

  const fetchItems = async () => {
    const data = await fetch('/');
    const items = await data.json();
    setItems(items);
  }


  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          {!items ? "Loading..." : items}
        </p>
      </header>
    </div>
  );
}

export default App;
  • I have set proxy at React to contact Node. I don’t know if there is a communication issue there.
  • I have seen network logs on browser but I don’t see request sent to node
  • I have added console logs at server but they don’t get printed when endpoint is suppose to be called
  • I have tried two version but none are working

I am running out of ideas.

2

Answers


  1. Chosen as BEST ANSWER

    I am happy to receive a better answer / explanation but it seems that if the route is / i.e. I fetch('/') the root path, it returns the index.html from the React public folder. If I use any other path, fetch('/api') for instance, proxy works and points to the Express server.

    Not sure if this is expected behavior, or why If it is?

    https://github.com/facebook/create-react-app/issues/1378


  2. You can start by looking at what’s in the data variable:

    const data = await fetch('/');
    console.log(data)
    const items = await data.json();
    

    and making sure that requests to the backend are handled correctly by sending an API request without using React, for example, using postman or if your are using VSCode, you can use an extension made for that purpose.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search