如何配置 vite.config 以代理不同端口上的服务器

3

我正在尝试从 Flask 服务器(localhost:5000)使用我的 Vite 应用程序(localhost:5173)获取数据。我所有的 API 端点在 Postman 中都有效。我遵循了 Vite 文档中的说明,但是我一定漏掉了什么,因为 fetch 仍然会发送请求到 localhost:5173。

这是 vite.config.ts 文件内容:

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      "/api": {
        target: "http://127.0.0.1:5000",
        changeOrigin: true,
        secure: false,
        ws: true,
        configure: (proxy, _options) => {
          proxy.on('error', (err, _req, _res) => {
            console.log('proxy error', err);
          });
          proxy.on('proxyReq', (proxyReq, req, _res) => {
            console.log('Sending Request to the Target:', req.method, req.url);
          });
          proxy.on('proxyRes', (proxyRes, req, _res) => {
            console.log('Received Response from the Target:', proxyRes.statusCode, req.url);
          });
        }
      },
    }
  }
})

这些是在vite.config中错误处理的客户端控制台输出:

Sending Request to the Target: GET /api/home/
Received Response from the Target: 200 /api/home/

这是我的获取函数:

fetch('/api/home')
      .then((res) => console.log(res))
    // .then((res) => res.json())
    // .then((data: object[]) => {
    //   setPostData(data)
    // })

这是上述console.log的输出(不明白为什么fetch仍然命中localhost:5173端点):
type: 'basic', 
url: 'http://localhost:5173/api/home/', 
redirected: true, 
status: 200,  ok: true, 

这是一些数据,它在Postman中的响应如下:

[{
        "comments": [],
        "created_at": "Thu, 23 Mar 2023 08:30:17 GMT",
        "likes": 2,
        "text": "Lorem ipsum",
        "title": "Morbi non quam nec dui luctus rutrum",
        "updated_at": "Thu, 23 Mar 2023 08:30:17 GMT",
        "user": "alesmonde0",
        "user_id": 1
    }]

我对Flask和TypeScript都不太熟悉,但是有使用Express和Node、有使用React/Vite的经验。

我试过:

  • 按照Vite文档进行操作
  • 在vite.config中将server.proxy路径更改为'/' - 这仅会提供我的Flask应用程序,没有Vite
  • 在vite.config中添加secure: false - 一位类似问题上我找到的解决方案 - 这并没有起作用
  • 在vite.config中添加ws: true - 在此处找到的另一个解决方案 - 没有起作用
  • 将server.proxy url从'/api'更改为'/' - 这提供了我的Flask应用程序,并且无法查看我的Vite前端
  • 在我的fetch中添加Access-Control-Allow-Origin头 - 这没有任何作用
  • 添加server.proxy.configure选项以尝试查找错误 - 这会混淆性地响应200 - 我预期会出现400
1个回答

0

我通过使用Axios成功解决了这个问题。这只需要配置Axios模块本身,而不是必须配置vite.config文件。

在React组件中进行获取:

import axios from 'axios';

async function fetch() {
      const res = await axios.get('http://127.0.0.1:5000/', {
        headers: { 'Content-Type': 'application/json' }
      });
      setPostData(res.data);
    }

我还必须在服务器端实现flask-CORS,以避免“Access-Control-Allow-Origin”错误:

app.py:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接