Home > Back-end >  Unable to call internal API with create-react-app
Unable to call internal API with create-react-app

Time:03-19

I'm having an issue calling fetch('/api') from my very basic create-react-app.

The issue I'm getting in console is GET http://localhost:3000/api 500 (Internal Server Error)

In my client/package/json I'm setting the proxy to "proxy": "http://localhost:3001", yet when I call /api it's trying to use port 3000 rather than 3001.

I have two servers running, the client at 3000 and the API at 3001 and when I go to localhost:3001/api I see the expected {message: "Hello from server!" } json in my browser

My client/src/App.js:

import React from "react";
import logo from "./logo.svg";
import "./App.css";

function App() {
  const [data, setData] = React.useState(null);

  React.useEffect(() => {
    fetch("/api")
      .then((res) => res.json())
      .then((data) => setData(data.message));
  }, []);

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

export default App;

My server/index.js:

const path = require('path');
const express = require("express");

const PORT = process.env.PORT || 3001;

const app = express();

// Have Node serve the files for our built React app
app.use(express.static(path.resolve(__dirname, '../client/build')));

app.get("/api", (req, res) => {
  res.json({ message: "Hello from server!" });
});

app.listen(PORT, () => {
  console.log(`Server listening on ${PORT}`);
});

Would love to know what I'm doing wrong here.

Thanks!

CodePudding user response:

You can modify your fetch request API url to give the complete hostname since

 fetch('http://localhost:3000/api/') 

Or you can use third-party proxy middleware. see this post https://medium.com/bb-tutorials-and-thoughts/react-how-to-proxy-to-backend-server-5588a9e0347

CodePudding user response:

The "proxy" setting described in the documentation should be set in the server package.json, not the client's. This is because the way the proxy work is that the server accepts the incoming request (on port 3000) and then turns around and proxies it to port 3001 on your behalf.

The client doesn't know it's being proxied.

Relevant bit from the documentation, with emphasis added:

To tell the development server to proxy any unknown requests to your API server in development, add a proxy field to your package.json...

  • Related