yarn - 配置本地代理路由到文件夹

1.yarn写法

在 proxy: { 同级位置添加

// 在这里添加本地文件路径映射
serverMiddleware: isDevMode ? [
{path: '/file', handler: serveStatic('D:/workSpace/xxx/files')},
{path: '/mom-file', handler: serveStatic('D:/workSpace/xxx/files')}
] : [],

在最外层添加判断条件

// 检测是否为开发模式
const isDevMode = process.env.NODE_ENV === 'development';

2.vue2写法

const configParam = {
    // 本地开发时,直连后台网关
    local: {
        target: "http://localhost:9102",
        pathRewrite: {
            '^/api/gateway': ''
        },
        // 映射磁盘路径
        beforeKv: [{
            key: '/api/attchFileApi/nginx/',
            val: 'D:/xxx/temp'
        }]
    },
    // 本地开发时,直连666服务器
    dev666: {
        target: "http://api.xxx.com:8080",
        pathRewrite: {
            '^/api/': '/'
        }
    }
}

const config = {...configParam.local};
参数定义,方便切换
proxy: {
    '/api': {
        target: config.target,
        changeOrigin: true,
        pathRewrite: {...config.pathRewrite},
        // 显示请求代理后的真实地址
        bypass(req, res, options) {
            let proxyUrl = new URL(req.url || "", options.target + "")?.href || "";
            if (config.pathRewrite && Object.keys(config.pathRewrite)) {
                let keyVal = ""
                let val = ""
                for (const key of Object.keys(config.pathRewrite)) {
                    keyVal = key.replace("^", "")
                    val = config.pathRewrite[key]
                    break
                }
                proxyUrl = proxyUrl.replace(keyVal, val);
            }
            res.setHeader("x-res-proxyUrl", proxyUrl);
        }
    }
},
before(app) {
    if (!config.beforeKv || !config.beforeKv.length) {
        return
    }
    for (const {key, val} of config.beforeKv) {
        app.use(key, express.static(val));
    }
},
代理时使用

3.vue3写法

暂定

 

posted @ 2026-02-02 15:12  岑惜  阅读(25)  评论(0)    收藏  举报