Mock-server
At the start of a new project, the backend framework is not available, and the front end has the service of simulating data that can operate on its own.
EXPRESS-MOCKJS is express+mock-lite
a combination of the building of a wheel, can quickly help us to build a mock server in the local
Related information:
- Express-mockjs
- Mock-lite
- Express
Install EXPRESS-MOCKJS to Project
Install Express-mockjs (v0.4.9):npm install express-mockjs --save-dev
Install Nodemon to project to listen for mock code modifications
Install Nodemon (v1.17.4):npm install nodemon --save-dev
New Mock-server/index.js writing startup server code
var path = require('path')var express = require('express')var mockjs = require('express-mockjs')var app = express()// 自定义路径 前缀: '/api'var config = { port: 3000}//以/api为前缀,寻找api目录下的所有接口app.use('/api', mockjs(path.join(__dirname, 'api')))// 获取port参数 可通过 --port自 定义启动端口var args = process.argvfor (let i = 0; i < args.length; i++) { if (args[i] === '--port' && i < args.length - 1 && args[i + 1] > 0) { config.port = args[i + 1] break }}console.log('mock-server[mockjs-lite]:http://localhost:' + config.port)// console.log('mockjs-lite定义:http://mockjs-lite.js.org/docs/examples.html')app.listen(config.port)
Writing interface files
Create the API folder in the Mock-server folder and install the EXPESS-MOCKJS documentation Json/js
Json
/** * Interface function description * * @url /api-access-path * * Parameter description and other instructions. * uid: user ID * name: username * email: the email * etc. */{ "code": 0, "result|5": [ { "uid|+1": 1, "name": "@name", "email": "@email" } ]}
Js
/** * home page links * * @url /home-links * * Here you can write a detailed description * of the parameters of the information. */module.exports = { code: function() { // simulation error code, 1/10 probability of error code 1. return Math.random() < 0.1 ? 1 : 0 }, 'list|5-10': [{ title: '@title', link: '@url' }]}
Running a mock server
Add a mock command to the Package.json of the project and run:npm run mock
"scripts": { "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js --host 0.0.0.0 --port 5555", //... "mock": "nodemon --watch mock-server node mock-server/index.js --port 6543" },
Code diagram
RELATED LINKS
The implementation of the article can be found in the following warehouse, not clear where you can directly view the source code
- Warehouse Source: Https://github.com/yimogit/me-admin-template
- Template preview: Https://vue-admin.yimo.link
Vue Project Practice-adding EXPRESS-MOCKJS for data simulation