How to implement background data sending in express+mockjs
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
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');
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 }] })); });
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))); } }) }) }) } })
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(); });
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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? 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

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

To use mockjs in vite to simulate data, you need to use new dependencies. 1. Install mockjsyarnaddmockjs-S or npmimockjs-D 2. Install vite-plugin-mocknpmivite-plugin-mock-D 3. In the src/mock/source folder Create user.ts and put the following content in index.vue: import{MockMethod}from'vite-plugin-mock'exportdefault[{url:'/api

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? 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 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 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
