使用devServer.before 模拟数据

2,241 阅读1分钟

官方介绍

官方地址:点这里 image.png

翻译:提供在服务器内部首先执行自定义中间件的能力。这可用于定义自定义处理程序,例如:

如何在项目里使用

工程目录结构:

image.png

一些全局配置写在.env 联调时改为false

VUE_APP_MOCK=true

vue.config.js

const IsMockMode = process.env.VUE_APP_MOCK === 'true';
const main={
    devServer:{
        // 联调环境暂不管
        // proxy: IsMockMode 
        //   ? null
        //   : {
        //       [`${process.env.VUE_APP_API_PREFIX}/*`]: {
        //         target: `http://10.15.80.24:17020`,
        //         // target: `http://10.33.43.58`,
        //         changeOrigin: true,
        //         secure: false,
        //         pathRewrite: {
        //           '^/api': '/'
        //         }
        //       }
        //     },
        before:IsMockMode ? require('./mock/index.js') : () => {},//联调时
    }
}
module.exports = main;

mock/index.js

const fs = require('fs');
const path = require('path');

module.exports = app => {
  app.all(/.*.do$/, (req, res) => {
    const JSFilePath = path.join(
      __dirname,
      `/api/v1${req.path.replace('/api/', '/').replace('.do', '.js')}`
    );
    if (fs.existsSync(JSFilePath)) {

      delete require.cache[JSFilePath];
      require(JSFilePath)(req, res);
    } else {
      res.send({
        code: '0',
        data: {},
        msg: '请求成功'
      });
    }
  });
};

接口文件夹创建 举例:当请求为http://localhost:8080/api/dzavc/alert/getDeptInfo.do 时,index.js处理后读取的文件夹为api/v1/dzavc/alert/getDeptInfo.js,因此我们将模拟数据写在该文件内即可。 image.png

测试

npm install axios
import axios from 'axios'
axios.get('/api/dzavc/alert/getDeptInfo.do').then(function (response) { 
    console.log(response); 
}).catch(function (error) {
    console.log(error); 
});


观察调试工具network的表现