This time I will show you how express mock operates front and backend parallel development, and what are the precautions for front and backend parallel development of express mock. The following is a practical case, let's take a look.
When our project is just started, because the backend has just started to be developed, our front-end often does not have data and interface requests during the development process, so we have to create some fake data or use mocks to create some data. But in this case, some useless code will often be included. It will have to be deleted by then.
Let’s introduce an express mock that allows front and backend to be developed in parallel.
We need to discuss the data format before and after, and a series of details. Let’s go straight to the code without further explanation
app.js
'use strict'; const express = require('express'); const app = express(); // port let NODE_PORT = process.env.PORT || 4000; // 监听 /user app.use('/user', function(req, res) { // 让接口 500-1000ms 返回 好让页面有个loading setTimeout(() => { res.json({ status: 1, msg: '查询成功', data: { name: '张三' } }); }, Math.random() * 500 + 500); }); app.listen(NODE_PORT, function() { console.log('mock服务在' + NODE_PORT + '端口上已启用!'); });
Next we Open the current file in the command window and run node app.js
Then open the browser and enter http://localhost:4000/user
to complete a simple Simulation data, next we improve the requirements
If we sometimes use different ports in local development, cross-domain problems will be reported, so we need to add some code inapp.js
const cors = require('cors'); app.use(cors({ origin: '*', methods: ['GET', 'POST', 'PUT', 'DELETE'], allowedHeaders: ['conten-Type', 'Authorization'] }));
In this way, you can access it on other ports or other IP intranets (you can access it at the same time).
If we need to access some static files, we can add some code
// './' 根据自己的需求自己配置 app.use(express.static(path.join(__dirname, './')));
// Configure nodeman hot update
var nodemon = require('nodemon'); nodemon({ script: 'app.js', ext: 'json js', ignore: [ '.git', 'node_modules/**' ], });
Next, we will continue to improve. In development, we cannot only An interface, so we are under optimization.
app.js
'use strict'; const express = require('express'); const cors = require('cors'); const path = require('path'); var nodemon = require('nodemon'); const userRoutes = require('./user'); const areaRoutes = require('./area'); const nameListRoutes = require('./name-list'); const app = express(); app.use(cors({ origin: '*', methods: ['GET', 'POST', 'PUT', 'DELETE'], allowedHeaders: ['conten-Type', 'Authorization'] })); // port let NODE_PORT = process.env.PORT || 4000; app.use(express.static(path.join(__dirname, './'))); app.use('/user', userRoutes); app.use('/area', areaRoutes); app.use('/nameList', nameListRoutes); nodemon({ script: 'app.js', ext: 'json js', ignore: [ '.git', 'node_modules/**' ], }); app.listen(NODE_PORT, function() { console.log('mock服务在' + NODE_PORT + '端口上已启用!'); });
We need to add the following files in the same directory ./user/index.js
, /user/area. Contents in js
, /name-list/index.js
##./user/index.js As follows
'use strict'; const express = require('express'); const Mock = require('mockjs'); const apiRoutes = express.Router(); let random = Math.random() * 500 + 500; // 访问 /user/ 时 apiRoutes.get('/', function(req, res) { setTimeout(() => { res.json({ status: 1, msg: '查询成功', data: { name: '张三' } }); }, random); }); // 访问 /user/1111 时 apiRoutes.get('/idList', function(req, res) { setTimeout(() => { res.json({ status: 1, msg: 'OK', data: Mock.mock({ 'list|1-10': [{ 'id|+1': 1 }] }) }); }, random); }); module.exports = apiRoutes;
## in the browser. Our preliminary simulation data is basically completed.
Next, you need to use it in the project
First distinguish the environment
// 判断是否是本地开发 const isDev = process.env.NODE_ENV ==='development'; // 设置 host 本地走mock 生产环境走相对路径 /user/ const host = isDev ? 'http://localhost:4000' : '' fetch(`${host}/user/`) .then(response => { return response.json(); }) .then(data => { console.log(data ); });
Assume we are accessing locally
The data is all available. Try accessing it from other domain names.
Cross-domain issues are also OK.
We are setting
package.json Add && node xx/aap.js
in the command background of your local development or run it in a separate command window I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How does Angular CLI implement an Angular projectHow to use jquery layur pop-up layer in actual projectsThe above is the detailed content of How express + mock operates front and backend parallel development. For more information, please follow other related articles on the PHP Chinese website!