devServer before mock 数据

145 阅读1分钟

image.png image.png

1、创建mock.config.js 文件 创建mock中间件

const path = require('path');

function response(res, content, type = 'json') {
    res.type(type);
    res.write(content);
    res.end();
}

function mock(res, file) {
    fs.readFile(file, 'utf8', (error, content) => {
        if (error) {
            response(res, error.message, 'html');
        }
        response(res, content, 'json');
    });
}

const mockMiddleware = (config) => (req, res, next) => {
    const { projectDir, mockDir } = config;

    if (['.html', '.css', '.js', '.png', '.jpg'].indexOf(path.extname(req.path)) > -1) {
        return next();
    }

    const filePath = path.resolve(projectDir, `./${mockDir + req.path}.json`);
    console.log('filePath', filePath);

    return fs.stat(filePath, (error) => {
        if (error) {
            next();
        } else {
            mock(res, filePath);
        }
    });
};

module.exports = mockMiddleware;

2、webpack.dev.config.js 配置引用中间件

const mockMiddleware = require('./mock.config');

const PORT = 8080;
    const webpackConfigDev = {
        devServer: {
        contentBase: path.join(__dirname, '../src'),
        historyApiFallback: false,
        hot: false,
        host: '0.0.0.0',
        port: PORT,
        before(app) {
            const projectDir = path.resolve();
            const mockDir = './mock';
            app.use(mockMiddleware({ projectDir, mockDir }));
        },
   },
}

3、创建本地mock文件

文件路径设置为ad/index/

gray.json

{
    "code": 0,
    "msg": "success",
    "data": {
        "gray": true
    }
}

4、测试 本地浏览器访问http://localhost:8080/ad/index/gray

5、文件中使用axios访问

    componentDidMount() {
        axios.get('/ad/index/gray').then((res) => {
            console.log('res', res);
        }).catch((error) => {
            console.log(error);
        });
    }