Generate random data using mock.js
This article mainly introduces the implementation method of using mock.js random data and using express to output json interface. Friends in need can refer to it
Front-end projects will use the back-end interface, but when the back-end interface When it is not written well, you can use mock.js to randomly generate some fake data to debug the page
Install mock.js
First use express to create a nodejs web project. If the name is demo, I won’t say it here.
yarn add mockjs
Use the random number above
const Mock = require('mockjs') var data = Mock.mock({ 'list|2': [{ 'id|+1': 1, 'color': '@color()', 'date': '@datetime()', 'img': '@image()', 'url': '@url(http)', 'email': '@email()', 'name': "@name(1,2)", 'text': '@paragraph()' }] }) console.log(JSON.stringify(data))
The method can be found in the link to the mockjs document given at the bottom. The method called by Mock.Random can be used directly by adding @ in front. It is very convenient.
Output
{ "list": [ { "id": 1, "color": "#8179f2", "date": "2015-06-22 12:10:08", "img": "http://dummyimage.com/250x250", "url": "http://hwujcvh.fk/vfrjfmi", "email": "y.ahbatuekk@mbkhfybrh.pl", "name": "James Ronald Rodriguez", "text": "Zsogshtw qjscoe qwggnfk ppbdpqd avftd pvczrvnu gsyfyefm rbnbjyy tgemy buple ieghyjp klcxauofu lhjmnb kjpyodk. Njync ysrvx jevei stawy mcosrlpo iacryqob wkkcfuh nkrrdutr zduikjvtf dcv pppbhi ygjnkmg xvpusp ayu lvu. Wgqmtwvo ibqzp cct kodyh ovz slo cpc uqaseuwv ubjgbf hihh oudly mooztiojpi tubmwhsmb kktbkyqp hsvwgoluu jrkosqudm. Wpumdvtw riytwoa sbittrr xtjy beorkb osnjpigntu ndrgxhozeq iufhu hpuirgmh lstoijpqx hopk lkxceqhvr uymj pgdms njjmu ivxijmokn." }, { "id": 2, "color": "#94f279", "date": "1980-02-20 19:46:44", "img": "http://dummyimage.com/336x280", "url": "http://voyqj.cx/jjyksqzur", "email": "k.ydgui@gixl.cr", "name": "Ronald Nancy Harris", "text": "Lbdpwqwpgd sodipqu oncnnyis ebtwho dnbt fqxnjyzr qtrriop gfbjt prto dgmtgff gwaqnhon sdlvpxpj pqomfflsc skj. Cvteunoj oqmjnfm vowvmw ypywtr klcazkvg cvsyzayytl bgvywe kfqqzhfg iahm jwury xsgf xnr pvfxwhaed nauookwi xuxtgnwq flcbmnrm qglgziy vegml. Cexit vdotefuj nptmei hekmljnt bukxrd ndhj lkfyjcv oldpgo rrj kprfklt nfks yvrvc. Aynbyd hxguza ftjrn kmlirqo wxald jqjkvahim jnhezpgm usev qbynwhm yotehgkwdg eyxj vfnm icchnds dgmd odxajing vqrdl yhpp eba. Tykxnhe njod bslwbsjcj rwlv rkvxk rypew fpfqrqi psislxuwgs jcwrbtfn qeszy leovhc jwupwzo kitct nhbdhjq xyiajxms. Gfgkw nnlg drcqnpwn bowqknwy oiw yysaohk fqqsbgvp mulik vusikwv nbp kpbo nhti dhf hrgql." } ] }
Integrated into express to output json
const Mock = require('mockjs') exports.index = function(req, res) { var data = Mock.mock({ 'list|2': [{ 'id|+1': 1, 'color': '@color()', 'date': '@datetime()', 'img': '@image()', 'url': '@url(http)', 'email': '@email()', 'name': "@name(1,2)", 'text': '@paragraph()' }] }) // 延时1秒,模拟网络请求时间 setTimeout(function() { res.send(JSON.stringify(data)) }, 1000); }
express cross-domain
Interface address and The front-end project address will definitely be different. At this time, the request interface will involve cross-domain issues. The solution in express is as follows
app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "http://localhost:8080"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("X-Powered-By",' 3.2.1') res.header("Content-Type", "application/json;charset=utf-8"); res.header('Access-Control-Allow-Credentials', true); next(); });
Description: The above code was found online, but there is no such thing found online. Sentence res.header('Access-Control-Allow-Credentials', true);
The address of my front-end project is http://localhost:8080, so the value of Access-Control-Allow-Origin is http: //localhost:8080
You can modify it according to your own server
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to generate a drop-down list with pure js
vuex’s detailed introduction Chinese document
How to solve the problem of Router cross-module jump
The above is the detailed content of Generate random data using mock.js. 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

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

Steps to connect MyCAT in Node.js: Install the mycat-ts dependency. Create a connection pool, specify the host, port, username, password and database. Use the query method to execute SQL queries. Use the close method to close the connection pool.

Node.js is suitable for the following project types: Network and server applications Event-driven applications Real-time applications Data-intensive applications Command-line tools and scripts Lightweight microservices
