


Example tutorial on mock.js random data and using express to output json interface
Front-end projects will all use the back-end interface, but when the back-end interface is not written well, you can use mock.js to randomly generate some fake data to debug the page. 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. I hope it can help everyone.
Install mock.js
First use express to create a nodejs web project. If the name is demo, I won’t go into it here
yarn add mockjs
Use
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 above random 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
The interface address will definitely be different from the front-end project address. At this time, requesting the 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(); });
Explanation: The above code was found online, but the sentence res.header('Access-Control-Allow-Credentials', true);## was not found online.
#The address of my front-end project is http://localhost:8080, so the value of Access-Control-Allow-Origin is http://localhost:8080It can be modified according to your own server. Related recommendations:Express and mockjs realize the simulation background data sending function example sharing
Detailed explanation of using nodejs+express to implement simple files Upload function
Detailed explanation of node.js using websocket based on express
The above is the detailed content of Example tutorial on mock.js random data and using express to output json interface. 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 use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

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
