我在我的存储库根目录中的 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/