vue.config.js 中的 Vue devServer.proxy 不起作用

Rya*_*ice 3 vue.js vite

我在存储库根目录中使用以下配置vue.config.js,但它不起作用。

  module.exports = {
    devServer: {
        proxy: "http://localhost:3030"
      }
  }
Run Code Online (Sandbox Code Playgroud)

这就是我试图称呼它的方式

  return await fetch("/posts", options).then((response) =>
    response.json()
  ).catch(e => console.log("Error fetching posts", e));
Run Code Online (Sandbox Code Playgroud)

但是,当我将调用代码更改为下面显示的代码时,一切正常

  return await fetch("http://localhost:3030/posts", options).then((response) =>
    response.json()
  ).catch(e => console.log("Error fetching posts", e));
Run Code Online (Sandbox Code Playgroud)

编辑

我应该提到我正在使用 Vite 进行构建,因为这给我带来了一些环境变量的其他问题,因此它们也可能导致代理出现问题。

我对此进行了更多研究,结果发现 Vite 确实具有代理功能,因此我尝试更新我的代码以使用他们的代理,但仍然没有成功。

// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  server: {
    "/posts": "http://localhost:3030/posts"
  }
})
Run Code Online (Sandbox Code Playgroud)

ton*_*y19 8

vue.config.js适用于 Vue CLI 脚手架项目(并且您的配置将在那里工作),而不是 Vite 项目。Vite 的配置存储在vite.config.js.

您的 Vite 配置值server.proxy包含不必要的/posts后缀:

"/posts": "http://localhost:3030/posts"
                                ^^^^^^
Run Code Online (Sandbox Code Playgroud)

该值应该只是附加原始路径的基本 URL:

"/posts": "http://localhost:3030"
Run Code Online (Sandbox Code Playgroud)

例子:

// vite.config.js
import { defineConfig } from 'vite'

export default defineConfig({
  server: {
    proxy: {
      '/posts': 'http://localhost:3030'
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

GitHub 演示