在前端开发中,有时候会需要mock接口,虽然有的工具提供了云端mock的功能,但是定制化比较低,所以我用node写了一个mock小工具,主要使用了express、mockjs、cors,
"cors": "^2.8.5",
"express": "^4.19.2",
"mockjs": "^1.1.0"
使用两个文件即可完成这个小功能
首先搭建一个简单的后端服务,这里使用express
server.js :
const express = require('express');
const Mock = require('mockjs');
const app = express();
const port = 3000;
const generateMockTemplate = require('./generateJson.js')
var cors = require('cors')
app.use(cors())
app.post('/mty/mtyOll', (req, res) => {
const userData = Mock.mock(JSON.parse(generateMockTemplate(
// json放这里----------------------------------------------------------
{
"msg": "",
"code": "",
"data": [
{
"id": "",
"userId": "",
"intCls": 0,
"intClsName": "",
"applicant": "",
"applicantType": 0,
"applicantAddress": "",
"brandApplicantNum": 0,
"brandRegNum": 0,
}
]
}
// json放这上边----------------------------------------------------------
)));
res.json(userData);
});
// 或者,如果你想要根据请求参数动态生成数据
app.get('/api/example', (req, res) => {
const userId = parseInt(req.params.id, 10);
// 假设我们只返回一个用户,根据ID随机匹配或生成
const user = Mock.mock({
'id': userId,
'name': '@cname',
'age|18-60': 1,
'city': '@city(true)',
'email': '@EMAIL'
});
res.json(user);
}
标签:node,const,后端,res,app,express,cors,mock
From: https://blog.csdn.net/weixin_43188912/article/details/144026605