Home > Web Front-end > JS Tutorial > body text

How to implement background data sending in express+mockjs

亚连
Release: 2018-06-13 14:09:14
Original
2642 people have browsed it

This article mainly introduces express mockjs to implement the simulated background data sending function. Friends who need it can refer to it

Foreword:

Most of the time, the front-end and back-end will be developed at the same time. That is to say, 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 Simulation data is required.

Simulating data method

1. Simulate background data through js variables

Advantages: No server required

Disadvantages: We need to create a lot of variables, and at the same time use the variables in our effective code, and finally delete them

2. Request json files through ajax

Advantages: Only configuration is required Path, you can access it, and you don’t need to modify a lot of js code when entering the joint debugging stage

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

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

Advantages: The front-end code only needs to enter the joint debugging stage A basePath needs to be modified. All interface names can be consistent with the agreed paths. You can test post requests and simulate the network environment

Disadvantages: You have to write a backend yourself

1 and 2 This method of simulating data is suitable for demos, 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 related 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 point we directly access http://localhost:8090/test.action, and you can see the text 'hello world' 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, when we access the page data again, we can get a random json data

6. Create the simulated data folder testData and create the simulated data json file (note: json file Regular expressions cannot be used, and the object attributes must be double-quoted strings)

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 When server.js runs the server, we can access the interface directly on the front end. However, if we just generate the backend and the front-end page is not accessed through the backend, there will be cross-domain problems. If we need to solve it, we 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

The above is what I compiled for everyone. I hope it will be useful to everyone in the future. helpful.

Related articles:

How to convert the path to base64 encoding in Javascript

Detailed interpretation of ie9 compatibility in VUE

How to configure vue scaffolding using parcel (detailed tutorial)

The above is the detailed content of How to implement background data sending in express+mockjs. For more information, please follow other related articles on the PHP Chinese website!

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