因为 Vue3 的构建工具是 Vite,所以配置 vue.config.js 是没用的(Vue2 因为使用 webpack 所以才用这个文件)

这里提供一份 vue.config.js 的示例:

注意使用 vue.config.js 的反代时需要删除 manifest.json 中 h5.devServer。否则运行时会优先使用 manifest.json 中的配置

module.exports = {
    devServer: {
        proxy: {
            '/api': {
                target: 'http://example.com',
                changeOrigin: true,
                pathRewrite: {
                    '^/api': '/',
                },
            }
        }
    }
}

同时 manifest.json 里配置的反代配置似乎有 Bug,反代能生效,但 path 重写是失效的,即:

{
    "h5": {
        "devServer": {
            "https": false,
            "disableHostCheck": true,
            "proxy": {
                "/api": {
                    "target": "http://example.com",
                    "pathRewrite": {
                        "^/api": ""
                    }
                }
            }
        }
    }
}

因为使用了 Vite,所以我们应该创建 vite.config.js 文件进行设置:

import { defineConfig } from 'vite';
import uni from '@dcloudio/vite-plugin-uni';

export default defineConfig({
    plugins: [
        uni()
    ],
    server: {
        host: '127.0.0.1',
        port: 5173,
        proxy: {
            '/api': {
                target: 'http://example.com',
                changeOrigin: true,
                rewrite: (path) => path.replace(/^\/api/, ''), // 此处进行路径重写
            }
        }
    }
});

至此重新运行服务即可看到生效并成功的反向代理,更多关于 Vite 反代配置看这里:https://cn.vitejs.dev/config/server-options#server-proxy

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐