vue.js - vue.config.js 中的 Vue devServer.proxy 不工作

我在我的存储库根目录中的 vue.config.js 中使用了以下配置,但它无法正常工作。

  module.exports = {
    devServer: {
        proxy: "http://localhost:3030"
      }
  }

这就是我想调用它的方式

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

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

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

编辑:

我应该提到我正在使用 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"
  }
})

最佳答案

vue.config.js 适用于 Vue CLI 脚手架项目(你的配置应该是 worked there ),不适用于 Vite 项目。 Vite的配置保存在vite.config.js中。

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

"/posts": "http://localhost:3030/posts"
                                ^^^^^^

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

"/posts": "http://localhost:3030"

示例:

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

export default defineConfig({
  server: {
    proxy: {
      '/posts': 'http://localhost:3030'
    }
  }
})

GitHub demo

https://stackoverflow.com/questions/67992023/

相关文章:

bash - 如何压缩和忽略 .gitignore 指定的所有文件

SQL - Like and greater than 函数

java - 刀柄不同步

r - tidyr::pivot_longer 到多列

javascript - 如何在 Vue 3 模板中使用导入函数?

scala - 使用选定元素将一个案例类转换为另一个案例类

algorithm - 斐波那契 : non-recursive vs memoized recur

python - 如何使 spaCy 匹配不区分大小写

javascript - 如何使用 Manifest v3 获取当前选项卡 URL?

python - 在python中获取每个月的最后一个星期五