用express和mockjs实现前端mock serve

本文介绍一种用express和mockjs实现模拟后端接口返回数据的思路,直接上代码:
1.在项目根目录新建文件夹:mock
2.在mock文件夹下新建mock.js和mockData.js文件
3.

//mock.js
const Mock = require('mockjs')
const express = require('express')
const mockData = require('./mockData')
const mockDatas = Object.entries(mockData)

const app = express()

mockDatas.forEach((item) => {
  app.all(item[0], (req, res) => {
    res.json(Mock.mock(item[1]))
  })
})

app.listen('8000', () => {
  console.log('mockServer start')
})
//mockData.js
module.exports = {
  '/api': {
    "id|1-100": 100,
    "boolean|1-2": true
    //更多mock用法参考mock官方文档:http://mockjs.com/
  }
  //...
}

4.在package.json文件中添加script脚本:

"scripts": {
    "serve:mock": "node ./src/mock/mock.js"
 },

end~

你可能感兴趣的:(JS,mock)