Home Web Front-end JS Tutorial How express + mock operates front and backend parallel development

How express + mock operates front and backend parallel development

Jun 07, 2018 am 09:36 AM
express

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 + '端口上已启用!');
});
Copy after login

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']
}));
Copy after login

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, './')));
Copy after login

// Configure nodeman hot update

var nodemon = require('nodemon');
nodemon({
 script: 'app.js',
 ext: 'json js',
 ignore: [
  '.git',
  'node_modules/**'
 ],
});
Copy after login

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 + '端口上已启用!');
});
Copy after login

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;
Copy after login
We are now accessing

## 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 );
 });
Copy after login

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 project


How to use jquery layur pop-up layer in actual projects

The 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use express to handle file upload in node project How to use express to handle file upload in node project Mar 28, 2023 pm 07:28 PM

How to handle file upload? The following article will introduce to you how to use express to handle file uploads in the node project. I hope it will be helpful to you!

In-depth comparison of Express and Laravel: How to choose the best framework? In-depth comparison of Express and Laravel: How to choose the best framework? Mar 09, 2024 pm 01:33 PM

In-depth comparison of Express and Laravel: How to choose the best framework? When choosing a back-end framework suitable for your project, Express and Laravel are undoubtedly two popular choices among developers. Express is a lightweight framework based on Node.js, while Laravel is a popular framework based on PHP. This article will provide an in-depth comparison of the advantages and disadvantages of these two frameworks and provide specific code examples to help developers choose the framework that best suits their needs. Performance and scalabilityExpr

Comparative analysis of Express and Laravel: Choose the framework that suits you better Comparative analysis of Express and Laravel: Choose the framework that suits you better Mar 10, 2024 pm 10:15 PM

Express and Laravel are two very popular web frameworks, representing the excellent frameworks of the two major development languages ​​of JavaScript and PHP respectively. This article will conduct a comparative analysis of these two frameworks to help developers choose a framework that is more suitable for their project needs. 1. Framework Introduction Express is a web application framework based on the Node.js platform. It provides a series of powerful functions and tools that enable developers to quickly build high-performance web applications. Express

Let's talk about how node+express operates cookies Let's talk about how node+express operates cookies Jun 22, 2022 am 10:01 AM

How does node+express operate cookies? The following article will introduce to you how to use node to operate cookies. I hope it will be helpful to you!

Express vs. Laravel: Comparing the advantages and disadvantages, which one will you choose? Express vs. Laravel: Comparing the advantages and disadvantages, which one will you choose? Mar 10, 2024 am 08:39 AM

Express vs. Laravel: Comparing the advantages and disadvantages, which one will you choose? In the field of web development, Express and Laravel are two frameworks that have attracted much attention. Express is a flexible and lightweight web application framework based on Node.js, while Laravel is an elegant and feature-rich web development framework based on PHP. This article will compare the advantages and disadvantages of Express and Laravel in terms of functionality, ease of use, scalability, and community support, and combine

How to build a full-stack JavaScript application using React and Express How to build a full-stack JavaScript application using React and Express Sep 26, 2023 pm 01:09 PM

How to use React and Express to build a full-stack JavaScript application Introduction: React and Express are currently very popular JavaScript frameworks. They are used to build front-end and back-end applications respectively. This article will introduce how to use React and Express to build a full-stack JavaScript application. We will explain step by step how to build a simple TodoList application and provide specific code examples. 1. Preparation before starting

How to build a simple blog system using Node.js How to build a simple blog system using Node.js Nov 08, 2023 pm 06:45 PM

How to use Node.js to build a simple blog system Node.js is a JavaScript runtime environment based on the ChromeV8 engine, which can make JavaScript run more efficiently. With the help of Node.js, we can build powerful server-side applications using JavaScript, including blogging systems. This article will introduce you to how to use Node.js to build a simple blog system and provide you with specific code examples. Press

Express or Laravel? Choose the backend framework that works best for you Express or Laravel? Choose the backend framework that works best for you Mar 10, 2024 pm 06:06 PM

When it comes to choosing a backend framework, both Express and Laravel are very popular choices. Express is a web application development framework based on Node.js, while Laravel is a web application development framework based on PHP. Both have their own advantages, and choosing the framework that best suits you requires considering many factors. The strengths of the Express framework are its flexibility and easy learning curve. The core idea of ​​Express is "small enough and flexible enough", and it provides a large number of middleware

See all articles