mock模拟测试

uni-app 使用mock模拟数据

mock官网

安装依赖

//使用axios发送  ajax
	  	cnpm install axios --save
	//使用mockjs产生随机数据
	  	cnpm install mockjs --save-dev
	//使用json5解决json文件,无法添加注释问题
	  	cnpm install json5 --save-dev

新建文件夹

在这里插入图片描述

代码如下

module.exports = {
    
    
    devServer: {
    
    
        before: require('./mock/index.js')//引入mock/index.js
    }
}

在这里插入图片描述

代码

const fs = require('fs');
const path = require('path');
const Mock = require('mockjs');//mockjs 导入依赖模块
const JSON5 = require('json5');
//读取json文件
function getJsonFile(filePath) {
    
    
    //读取指定json文件
    var json = fs.readFileSync(path.resolve(__dirname,filePath), 'utf-8');
    //解析并返回
    return JSON5.parse(json);
}

//返回一个函数
module.exports = function(app){
    
    
    //监听http请求
    app.get('/user/userinfo', function (rep, res) {
    
    
        //每次响应请求时读取mock data的json文件
        //getJsonFile方法定义了如何读取json文件并解析成数据对象
        var json = getJsonFile('./userInfo.json5');
        //将json传入 Mock.mock 方法中,生成的数据返回给浏览器
        res.json(Mock.mock(json));
    });
}

在这里插入图片描述

{
    
    
    id: "@id()",
}

引用

在这里插入图片描述

<script>
	import axios from 'axios'
	export default {
    
    
		data() {
    
    
			return {
    
    
				title: 'Hello'
			}
		},
		onLoad() {
    
    

		},
		methods: {
    
    

		},
		mounted() {
    
    
			axios.get('/user/userInfo')
				.then(res => {
    
    
					console.log(res)
				})
				.catch(err => {
    
    
					console.error(err);
				})
		}
	}
</script>

猜你喜欢

转载自blog.csdn.net/weixin_44135909/article/details/112852044