vbenjs / vite-plugin-mock

A mock plugin for vite.use mockjs.
MIT License
621 stars 96 forks source link

如果本地开发环境配置了proxy,并进行了rewrite,那么应该如何做才能使用mock数据而不是使用后台server的数据呢? #55

Closed kaizige10 closed 3 years ago

kaizige10 commented 3 years ago

我的vite配置类似这样:

server: {
        host: serverJson.domain,
        port: serverJson.httpsPort,
        strictPort: true,
        proxy: {
            '^/ShoppingMall/api/': {
                    target: 'http://1.2.3.4:8080/',
                    changeOrigin: true,
                    ws: true,
                    secure: false,
                    rewrite: (path) => {
                        let _path = path;
                        _path = path.replace(/\/ShoppingMall/, "/");
                        console.log(`[vite.config.js proxy] rewrite path : ${_path}`);
                        return _path;
                    },
                };
        },
    plugins: [
        // 支持本地mock
        viteMockServe({
            mockPath: 'mock',
            localEnabled: true,
            watchFiles: true,
            logger: true,
        }),
    ],
}

mock文件夹下有一个test.js:

export default [
    {
        url: '/api/queryProductList',
        method: 'post',
        response: ({ query }) => {
            return {
                retCode: 0,
                total: 1,
                productInfoList: [
                    {
                        id: '1',
                        productType: 'phone',
                        productName: 'xiaomi 11',
                    },
                ],
            };
        },
    },
];

原本这样做,请求都会转发到后台服务的http://1.2.3.4:8080/api/xxxx,我加了vite-plugin-mock以后,没有什么变化,还是请求到后台http://1.2.3.4:8080/api/xxxx

kaizige10 commented 3 years ago

应该是我的用法不对,我再看下源码,看看如何解决

kaizige10 commented 3 years ago

确实是用法不对,我的mock文件里面,url是写死的'/api/queryProductList',实际上我收到的请求是/ShoppingMall/api/queryProductList,所以把url换成正则去匹配就可以了:url: /.*api\/queryProductList$/