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>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值