前端超简单写mock(使用express)
个人自己研究的mock写法,不需要做增删改,只需要返回值的情况,这样的写法可以极速实现mock
npm i -D express
index.js
const express = require('express');
const router = require('./router');
const app = express();// 允许跨域
app.all('*', (req, res, next) => {res.header('Access-Control-Allow-Origin', '*');res.header('Access-Control-Allow-Headers', 'Content-Type');res.header('Access-Control-Allow-Methods', '*');res.header('Content-Type', 'application/json;charset=utf-8');next();
});app.use(router);app.listen(80, () => {console.log('serve running at http://127.0.0.1');
});
把api文件夹下的所有js文件,注册路由
const express = require('express')
const router = express.Router()function routerPost(url) {const pathArr = url.split('/')const lastPathName = pathArr[pathArr.length - 1]router.post(url, (req, res) => {res.send(require('./api/' + lastPathName))})
}
routerPost('/heloworld/a')
routerPost('/heloworld/b')
routerPost('/heloworld/c')
routerPost('/heloworld/d')
routerPost('/heloworld/e')
module.exports = router
api文件夹下的js,比如a.js
module.exports = {msg: "操作成功",code: 200,data: ["1", "2", "3", "4"],
}
则axios.post(‘/heloworld/a’)返回
{msg: "操作成功",code: 200,data: ["1", "2", "3", "4"],
}
package.json加入脚本,npm run mock后启动express
"scripts": {..."mock": "npx nodemon ./mock/src/index.js"},