Front-end first mock interface (mock+express+json)

Table of contents

mock simulated data: data/static.js

Route: index.js

Server: server.js

yarn /node start server: yarn start

Client: Modify the proxy path (you must restart after modifying the settings to take effect)

Example

The backend framework express builds the server

The front end initiates a request

Static data: res.status === 304

3xx status code: redirect + cache

301 Moved Permanently: permanent redirection, search engines will update

302 Found: Temporary redirect, search engines usually do not update the index

304 Not Modified: The resource has not been modified and local cache can be used.

JSON parsing and generation

JSON generation JSON.stringify(value,replacer?,space? )


Image · nuysoft/Mock Wiki · GitHub

Applicable to the front-end first, there is a mock set in the api 

mock simulated data: data/static.js

// 导入 Mock 模块
import Mock from 'mockjs'

// 获取 Random 对象
const Random = Mock.Random

// 生成随机 ID、邮箱、IP、城市、日期时间等数据
//Random.id() 再@id  等价于 直接使用  Random.id(),推荐用@id,简洁
Random.id()
Random.email()
Random.ip()
Random.city()
Random.datetime()
Random.now()
Random.cname()

// 手机号前缀列表
const phonePrefix = ['132', '135', '189']
//Math.random() 函数返回一个 0 到 1 之间的随机小数
//index索引值将被用来选择一个前缀。
const index = Math.floor(Math.random() * phonePrefix.length)
//随机的8位数字串
const phone = phonePrefix[index] + Mock.mock(/\d{8}/)

// 静态数据对象
const static_data = {
  // 登出模拟数据
  logout: {
    // 从[0, 200]中随机选择一个元素作为模拟数据
    "code|1": [0, 200],
    "data": null,
    "message|1": ["执行成功"]
  },
  // 登录模拟数据
  login: {
    "code": 1,
    "data": {
        "datas": [{
            "user": {
                "status": 1,
                "userid": "@id",
                "userName": Random.string('lower', 5),  // 随机小写字母用户名
                "createTime": "@datetime",  // 随机日期时间
                "modifyTime": "@now",  // 当前时间
                "leader|1": [true, false]  // 随机领导状态
            },
            "resources": null
        }]
    },
    "message": "执行成功"
  },
  // 用户信息模拟数据
  info: {
    "code": 1,
    "data": {
        "datas": [{
            "userid": "@id",
            "userName": Random.string('lower', 5),  // 随机小写字母用户名
            "realName": "@cname",  // 随机中文姓名
            "createTime": "@datetime",  // 随机日期时间
            "modifyTime": "@now",  // 当前时间
            // @id() 是 Mock.js 提供的一个占位符,用于生成一个随机的唯一标识符。与之前的 @id 不同,这里使用了括号,这表示它会生成一个新的唯一标识符,而不是使用同一个。
            "orgId": "@id()",  // 随机组织 ID
            "email": "@email",  // 随机邮箱
            "phone": phone,  // 随机手机号
            // true,生成的城市名会带有省份,例如:"广东省深圳市"
            "city": "@city(true)",  // 随机城市名
            "ip": "@ip",  // 随机 IP 地址
            "leader|1": [true, false]  // 随机领导状态
        }]
    },
    "message": "执行成功"
  }
}

// 生成模拟数据并导出
let loginMock = Mock.mock(static_data.login),
    logoutMock = Mock.mock(static_data.logout),
    infoMock = Mock.mock(static_data.info)

export {
  loginMock,
  logoutMock,
  infoMock
}

// 使用Mock.mock来生成模拟数据
const data = Mock.mock({
  code: 1,
  data: {
      pid: '@id',           // 生成随机的ID
      date: Random.now(),   // 生成当前时间
      'list|1-10': [{       // 生成1到10个对象的数组
          'id|+1': 1,        // 从1开始,递增生成id
          'valiue|+1': Random.increment()  // 使用Random.increment()生成递增的值
      }]
  },
  message: 'succ'         // 设置消息
})

const getItem = JSON.stringify(data, null, 4)

Route: index.js

import { loginMock, logoutMock, infoMock } from './data/static.js'
// 定义 user 函数,用于处理路由和请求
const user = function (app) {
    // 登录
    app.get('/api/user/login', (req, res) => {
        res.send(loginMock);
    });

    // 用户信息
    app.get('/api/user/info', (req, res) => {
        res.send(infoMock);
    });

    // 退出
    app.get('/api/user/logout', (req, res) => {
        res.send(logoutMock);
    });
};

export default user

Server: server.js

Both node/express can be implemented, and express has less code.

import express from 'express'
import bodyParser from 'body-parser'
// chalk加颜色的
import chalk from 'chalk'

// 创建一个Express应用程序实例
let app = express();
// 使用body-parser中间件解析urlencoded和json请求体
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// 用户权限
import user from './user/index.js';
user(app);

// 首页
import home from './home/index.js';
home(app);

// 上传
import upload from './upload/index.js';
upload(app);


// 监听端口以便接受HTTP请求
// 启动监听
app.listen(5899, () => {
    console.log(chalk.blue('Express mock server listening on port 5899'));
});

yarn /node start server: yarn start

Client: Modify the proxy path (you must restart after modifying the settings to take effect)

​​​​​​​

const configStatic = {
  title: '后台',  // 网站的标题
  icon: '//c/favicon.ico',  // 网站的图标路径
  publicPath: {
    development: '/',  // 开发环境的公共路径
    online: '//ment/',  // 在线环境的公共路径
    uat: '//jment/uat',  // UAT环境的公共路径(User Acceptance Testing”(用户验收测试))
    test: '//ent/test'  // 测试环境的公共路径
  },
  proxy: {
    '/api': {  // 代理规则,将以 /api 开头的请求转发到指定的目标地址
      target: 'http://localhost:5899',  // 代理的目标地址
      changeOrigin: true,  // 设置请求头中的 Origin 字段为目标地址,用于处理跨域
      //pathRewrite: {
      // '^/api': '/'  // 修改请求路径,将 /api 替换为空字符串
      //}
    }
  }
}

module.exports = configStatic

Example

The backend framework express builds the server

// 引入所需的模块和数据
import express from 'express';
import { applyConfMock } from './data/static.js';

const app = express();
const port = 3000; // Replace with your desired port number

// 处理 POST 请求
app.use(express.json());

app.post('/api/upload/applyconf', (req, res) => {
  const id = req.body.id; // Get the id from the request body
  const result = applyConfMock[id]; // Use the id to get the corresponding data
  res.send(result);
});

// 启动服务器
app.listen(port, () => {
  console.log(`Server is listening at http://localhost:${port}`);
});

The front end initiates a request

const id = 123; // Replace with the actual id value
const data = { id: id }; // Create an object with the id property

fetch('/api/upload/applyconf', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => {
  // Handle the response result
})
.catch(error => {
  // Handle errors
});

Static data: res.status === 304

axiosThe library will process 304 responses by default and will not return the content of the 304 status code, but directly use the previously cached data.

3xx status code: redirect + cache

301 Moved Permanently: permanent redirection, search engines will update

302 Found: Temporary redirect, search engines usually do not update the index

304 Not Modified: The resource has not been modified and local cache can be used.

JSON parsing and generation

var str = '{"name": "参宿","id":7}';      //'JSON字符串'
var obj = JSON.parse(str);                //JSON.parse(str)
console.log(obj);                       //JSON的解析(JSON字符串转换为JS对象)

//Object { name: "参宿", id: 7 }
var jsonstr = JSON.stringify(obj);        //JSON.stringify(obj)
console.log(jsonstr);                     //JSON的生成(JS对象转换为JSON字符串)

JSON.parse(text[, reviver])//reviver函数参数,修改解析生成的原始值,调用时机在 parse 函数返回之前。
//k:key,v:value
JSON.parse('{"p": 5}', function (k, v) {
    if(k === '') return v;     // 如果到了最顶层,则直接返回属性值,
    return v * 2;              // 否则将属性值变为原来的 2 倍。
});                            // { p: 10 }

//从最最里层的属性开始,一级级往外,最终到达顶层,也就是解析值本身
JSON.parse('{"1": 1, "2": 2,"3": {"4": 4, "5": {"6": 6}}}', function (k, v) {
    console.log(k); // 输出当前的属性名,从而得知遍历顺序是从内向外的,
                    // 最后一个属性名会是个空字符串。
    return v;       // 返回原始属性值,相当于没有传递 reviver 参数。
});

// 1
// 2
// 4
// 6
// 5
// 3
// ""

JSON generationJSON.stringify(value,replacer?,space?)

  1. value: JavaScript object, array, string, number, boolean or null.
  2. replacer(Optional): A function or array that controls attribute filtering and conversion operations during the conversion process.
  3. space(Optional): Used to control the formatting of the output string, which can be a string or a number.

If it is a number, it indicates the number of spaces for indentation;

If it is a string, it means to use the string as indentation.

const data = {
    name: "Alice",
    age: 25,
    address: "123 Main St",
    secretInfo: "This is a secret"
};

// 使用 replacer 函数来过滤掉 secretInfo 属性
const jsonStringWithReplacer = JSON.stringify(data, (key, value) => {
    if (key === "secretInfo") {
        return undefined; // 过滤掉 secretInfo 属性
    }
    return value;
}, 2);

console.log(jsonStringWithReplacer);

const data = {
    name: "Bob",
    age: 28,
    hobbies: ["coding", "gaming"],
    address: "456 Elm St"
};

// 使用 replacer 数组来只保留 name 和 hobbies 属性
const jsonStringWithArrayReplacer = JSON.stringify(data, ["name", "hobbies"], 2);

console.log(jsonStringWithArrayReplacer);
import Mock from 'mockjs'

// 定义模板
const template = {
    'list|1-10': [{}]
}

// 生成模拟数据,转换为 JSON Schema 格式的数据
// JSON Schema 来验证它是否符合预期的数据结构
const data = Mock.toJSONSchema(template)

// 测试日志
console.log(JSON.stringify(data, null, 4))

Guess you like

Origin blog.csdn.net/qq_28838891/article/details/132176020