SoFunction
Updated on 2025-03-02

MockJs combines json-server to simulate background data

This article shares the specific code of MockJs combined with json-server to simulate background data for your reference. The specific content is as follows

illustrate

It is a simulation data generator that can generate data based on templates, simulate network requests, return simulated data, etc.
More details reference

Official website
Example

1. Installation

download

mkdir moke-test
cd moke-test
npm init
sudo npm install --save-dev json-server mockjs ip
mkdir server #Create a local service folder

2. Configure json-server

exist moke-test/server Created below

// 
const path = require('path');
const jsonServer = require('json-server');
const ip = require('ip').address();
const DB = require('./');
const server = ();
const router = (DB()); // Pass the created data object in to generate the corresponding routeconst middlewares = ();

 ();
 (middlewares);

 (router);

 ({
 host: ip,
 port: 3122
 }, function() {
 (`JSON Server is running in http://${ip}:3122`);
 });

In the same directory (moke-test/serverCreated under ) Files are used to generate data through mockjs

 // 
 const Mock = require('mockjs');
 const Random = ;

  = function () {
 const data = ({
  'id|+1': 0
 });

 return {data};
 }

3. Use mockjs to generate fake data dynamically

There are two ways to generate fake data

Data template definition
Data placeholder definition

1. Data template definition

The basic structure is as follows, please see the detailsOfficial website

 ({
 'name|rule': value
 })
 /*
  name: attribute name
  rule: Generate rules
  value: attribute value
  */

2. Data placeholder definition

Placeholders only occupy a position in the attribute value string and do not appear in the final attribute value.

1) Use @ to identify the following string as a placeholder, and spaces are separated between the placeholders
2) Placeholder is the method in
3) Use () to expand the placeholder
4) Placeholders can also refer to properties in the data template and use them first.

({
 'list|5': [{
  first: '@FIRST', // Can be capitalized }]
 })

3. Detailed explanation of tool categories

 // 
 const Mock = require('mockjs');
 const Random = ;

  = function () {
 // for custom extensions  ({
  courses: ['Music class', 'Dance class', 'Geography class'],
  course: function(date){
  return ()
  }
 });

 const courses = ({
  startClass: '@bool', // Boolean value, you can pass in parameters to set frequency  token: '@string("upper", 2, 8)', // Random string  createData: '@datetime("yyyy-MM-dd A HH:mm:ss")', // Return to date  image: '@image("200x100")', // Simulation picture 'x' link  manager: '@cname', // Chinese name  'partners|3': [
  '@name' // English name  ], 
  website: '@url',
  email: '@email',
  'password|2': '**', // Under the data template, the value is a string that means repeating the string according to the rules  'contents|1-20': [{ // Under the data template, the value of the array or the object rule part stipulates the number of elements displayed.  'id|+1': 0, // Under the data template, the value is a numerical value to represent the initial value or base number (divided by the rules of the move)  courseType: '@COURSE ', // Use extension  courseName() { // The value can be a function to simulate data in detail   return  + ' ' + (1, 10) + 'class'
  },
  name: '@courseType @natural(1, 10) class', // Multiple placeholders can be used at the same time, separated by spaces  'teacher': '@cname',
  position: '@courseType The @id classroom', // Reference the content in the current data template  students: /\d{5,10}/, // Use regular data format  classTime: '@datetime("M month d starts every Wednesday HH:mm")'
  }]
 })

 return {courses};
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.