Typescript, React, Vite, Express: 无法在前端获取数据

huangapple go评论88阅读模式
英文:

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

问题

我用Express在后端和React在前端使用TypeScript构建应用程序,并使用Vite来构建前端(我第一次使用Vite)。我的API正常工作,但我无法在前端获取数据。在前端的简化代码如下:

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

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

  fetchData();
}, []);

它一直在响应中发送给我这段 HTML:

<!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>

我尝试在我的 HTML 文件中添加了提到的脚本,但错误仍然存在。我不确定是否可能是在vite.config.ts文件中:

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

我已经在package.json文件中允许了代理以处理CORS,但似乎这并不是问题所在。我认为我可能忽视了一些重要的东西,但我不确定是什么...有人可以帮忙吗?

英文:

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(() =&gt; {
    const fetchData = async () =&gt; {
      const response = await fetch(&quot;/api/data&quot;);
      const json = await response.json();

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

    fetchData();
  }, []);

It keeps sending me this html in the response:

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
  &lt;head&gt;
    &lt;script type=&quot;module&quot;&gt;
import RefreshRuntime from &quot;/@react-refresh&quot;
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () =&gt; {}
window.$RefreshSig$ = () =&gt; (type) =&gt; type
window.__vite_plugin_react_preamble_installed__ = true
&lt;/script&gt;

    &lt;script type=&quot;module&quot; src=&quot;/@vite/client&quot;&gt;&lt;/script&gt;

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

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: &quot;dist&quot;,
  },
  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?

答案1

得分: 1

你会想在你的Vite配置中设置代理。

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

假设你的 API 监听在 3000 端口,将以下 proxy 属性添加到你的 server 对象中:

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

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: {
    &#39;/api&#39;: {
      target: &#39;http://localhost:3000&#39;,
      changeOrigin: true,
      secure: false
    }
  }
}

huangapple
  • 本文由 发表于 2023年2月7日 04:26:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75366217.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定