Home > headlines > Example sharing of express and mockjs to implement simulated background data sending function

Example sharing of express and mockjs to implement simulated background data sending function

小云云
Release: 2018-01-09 09:28:15
Original
2201 people have browsed it

Most of the time, the front-end and back-end will be developed at the same time. That is, when we finish developing the page, we may not be able to enter the joint debugging stage immediately. At this time, in order to ensure the effectiveness of our interface and the complete function of the code , we may need to simulate data. This article mainly introduces express+mockjs to implement the simulated background data sending function. Friends who need it can refer to it. I hope it can help everyone.

Simulating data method

1. Simulate background data through js variables

Advantages: No server required

Disadvantages: Need to create a lot of variables, and at the same time Use the variable in our valid code, and finally delete it

2. Request the json file through ajax

Advantages: You only need to configure the path to access it, and there is no need to modify it when entering the joint debugging stage A large amount of js code

Disadvantages: Ajax has cross-domain problems and usually cannot request local files. Even Firefox cannot access json files in different file directories. Usually, you need to start the service manually through IDE or yourself

3. Use nodejs to write a service specifically for sending requests, without business logic

Advantages: When the front-end code enters the joint debugging stage, you only need to modify a basePath, and all interface names can be the same as The agreed path remains consistent, you can test post requests and simulate the network environment

Disadvantages: You have to write a backend yourself

1 and 2 two methods of simulating data are suitable for demo, but If it is an online project, we still recommend building a node backend by yourself

1. Prepare the node environment, npm/cnpm

2. Install express and mockjs

3. Create the server file server.js and introduce relevant modules

let express = require('express'); //引入express模块
let Mock = require('mockjs');  //引入mock模块
let app = express();    //实例化express
Copy after login

4. Configure interface routing and set the listening port

/**
 * 配置test.action路由
 * @param {[type]} req [客户端发过来的请求所带数据]
 * @param {[type]} res [服务端的相应对象,可使用res.send返回数据,res.json返回json数据,res.down返回下载文件]
 */
app.all('/test.action', function(req, res) {
 res.send('hello world');
});
/**
 * 监听8090端口
 */
app.listen('8090');
Copy after login

At this time we directly access http ://localhost:8090/test.action, you can see the 'hello world' text directly on the interface

5. Use mockjs to return formatted json data

app.all('/test.action', function(req, res) {
 /**
  * mockjs中属性名‘|'符号后面的属性为随机属性,数组对象后面的随机属性为随机数组数量,正则表达式表示随机规则,+1代表自增
  */
 res.json(Mock.mock({
  "status": 200,
  "data|1-9": [{
   "name|5-8": /[a-zA-Z]/,
   "id|+1": 1,
   "value|0-500": 20
  }]
 }));
});
Copy after login

At this time we will visit again Page data, we can get a random json data

6. Create the simulated data folder testData and create the simulated data json file (note: regular expressions cannot be used in the json file, and the object attributes must be double quotes String)

7. Traverse the simulation data file and generate the corresponding route

/*readdir读取目录下所有文件*/
fs.readdir('./testData', function(err, files) {
 if(err) {
  console.log(err);
 } else {
  /*成功读取文件,取得文件名,拼接生成对应action,监听对应接口并返回对应文件数据*/
  files.forEach(function(v, i) {
   app.all(`/${v.replace(/json/, 'action')}`, function(req, res) {
    fs.readFile(`./testData/${v}`, 'utf-8', function(err, data) {
     if(err) {
      console.log(err);
     } else {
      res.json(Mock.mock(JSON.parse(data)));
     }
    })
   })
  })
 }
})
Copy after login

At this point, our node server has been successfully built. Using node server.js to run the server, we can directly run the front-end Access interface, but if you just simply generate the backend and the front-end page is not accessed through the backend, there will be cross-domain problems. If you need to solve it, you can add cross-domain requests in the backend

/*为app添加中间件处理跨域请求*/
app.use(function(req, res, next) {
 res.header("Access-Control-Allow-Origin", "*");
 res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
 res.header("Access-Control-Allow-Headers", "X-Requested-With");
 res.header('Access-Control-Allow-Headers', 'Content-Type');
 next();
});
Copy after login

ps: If mock needs to use regular expressions , please configure routing separately for processing. For more instructions on express and mockjs, please check the official website api

Related recommendations:

How jquery ajax returns background data Detailed explanation of the front-end table example code

Share a piece of code that jQuery Ajax requests background data and receives in the foreground

Using Angular to obtain local Localstorage data in real time , to achieve the effect of simulating background data login

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template