node 搭建mock servers

一、背景

mock数据在前端需求前期开发的中,发挥着重要的角色。是前后台同时开发,必不可缺少的环节。市面上也有很多第三方的mock数据的库,功能很多,库也大,接入复杂。所以可以使用node搭建一个简便的生成mock的服务器。(还有一种是直接使用接口管理工具提供的mock servers,比如YAPI,APIFOX,这种方式是比较推荐的。)

二、使用的技术

node koa koa-router koa-cors koa-badyparser koa-static

三、核心代码

const Koa = require('koa')
const app = new Koa()
const KoaRouter = require('koa-router')
const router = new KoaRouter()
const cors = require('koa2-cors')
const bodyparser = require('koa-bodyparser')
const staticKoa = require('koa-static') // 处理静态资源
// 静态文件处理
function staticPath(path){
  app.use(staticKoa(path))
}

app.use(bodyparser())
// 跨域
app.use(cors({
  origin: function(ctx) {
    // 这里用 headers 和 header 属性皆可
    return ctx.header.origin
  }
}))

app.use(router.routes()) // 启动路由
app.use(router.allowedMethods())
app.listen(9000, console.log('application is start at port 9000'))

module.exports = {
  router,
  app,
  staticPath
}

四、使用方式

安装

npm i ff-koa

导入

import myKoa from 'ff-koa/lib/mock.js'
const router = myKoa.router

mock数据返回示例

const users = {
  'superadmin-token': {
    permission: [1],
    introduction: 'I am a super admin',
    name: '超级管理员'
  },
  'admin-token': {
    permission: [2],
    introduction: 'I am an admin',
    name: '管理员'
  },
}
router.post('/user/login', ctx => {
  const { username } = ctx.request.body
  const token = tokens[username]
  ctx.body = fhcode(token)
})

五、其他

import myKoa from 'ff-koa/lib/mock.js'
myKoa.staticPath('../dist')

myKoa.staticPath(‘…/dist’)是启动打包文件的。
使用场景:
测试线上打包文件是否正常,有以下几种方式:
1、将打包dist文件使用nginx发布服务
2、使用browser-sync运行文件

npm install -g browser-sync

// 终端运行
browser-sync start --server --files "*.css, *.html , *.js" --reload-delay 800 -no-ghost-mode --open external --host= I P

3、使用mock数据,启动mock服务,配置打包文件路径’…/dist‘,运行127.0.0.1:9000 即可运行打包文件。

9000端口可自定义,定义方式:

import myKoa from 'ff-koa/lib/mock.js'
const app = myKoa. app
app.listen(9001)

说明:mock服务只需要根据业务需求选择合适的mock数据方式。并不局限于某一种。其目的就是为了提高开发的效率,能解决前后端同时开发的问题。

相关技术NPM包:
自动路由
接口模拟请求mock数据
vue脚手架

猜你喜欢

转载自blog.csdn.net/wang15180138572/article/details/125844657