【问题标题】:Typescript, React, Vite, Express: Cannot fetch data on the frontendTypescript、React、Vite、Express:无法在前端获取数据
【发布时间】:2023-02-07 08:43:25
【问题描述】:

我正在构建一个应用程序,后端使用 Express,前端使用打字稿 React,我正在使用 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,但这似乎不是问题所在。我想我忽略了一些重要的事情,但我不确定是什么......有人可以帮忙吗?

【问题讨论】:

    标签: reactjs typescript express vite


    【解决方案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
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-06
      • 1970-01-01
      • 2021-07-01
      • 2022-01-21
      • 2019-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多