boolie29
boolie29

Reputation: 55

Typescript, React, Vite, Express: Cannot fetch data on the frontend

I am building an app with Express on the backend and React on the frontend with typescript, and I am using Vite to build the frontend (my first time using Vite). My APIs are working fine, yet I am unable to fetch the data on the frontend. The simplified code on the frontend:

 React.useEffect(() => {
    const fetchData = async () => {
      const response = await fetch("/api/data");
      const json = await response.json();

      if (response.ok) {
        setData(json);
      }
    };

    fetchData();
  }, []);

It keeps sending me this html in the response:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script type="module">
import RefreshRuntime from "/@react-refresh"
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
</script>

    <script type="module" src="/@vite/client"></script>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React + TS</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx?t=1675714554862"></script>
  </body>
</html>

I have tried to add the mentioned scripts in my html file, but the error persits. I am not sure if it could be maybe in the vite.config.ts:

export default defineConfig({
  build: {
    outDir: "dist",
  },
  server: {
    port: 3001,
  },
  plugins: [react()],
});

I have allowed proxy in the package.json file to handle CORS but that doesn't seem to be the problem. I think I am overlooking something important but I am not sure what...Can anybody help?

Upvotes: 2

Views: 2019

Answers (1)

Wesley LeMahieu
Wesley LeMahieu

Reputation: 2613

You'll want to setup a proxy inside your Vite config.

https://vitejs.dev/config/server-options.html#server-proxy

Assuming your API listens on port 3000, add this proxy property to your server object:

server: {
  proxy: {
    '/api': {
      target: 'http://localhost:3000',
      changeOrigin: true,
      secure: false
    }
  }
}

Upvotes: 2

Related Questions