背景:
在react+webpack项目中前端如何mock数据,以模拟整体项目运行流程,不用等待后端人员提供接口。
解决方法:
本文使用 mocker-api mock数据接口。下面说明在项目中如何使用。
- 安装mocker-api插件
在项目中安装mocker-api插件
npm install mocker-api --save-dev
- 项目中新建mock文件夹,在该文件夹中新建mocker.js文件,用来mock数据以及接口。该文件格式如下:
const proxy = {
'GET /api/user': { id: 1, username: 'kenny', sex: 6 },
'GET /api/user/list': [
{ id: 1, username: 'kenny', sex: 6 },
{ id: 2, username: 'kenny', sex: 6 }
],
'POST /api/login/account': (req, res) => {
const { password, username } = req.body
if (password === '888888' && username === 'admin') {
return res.send({
status: 'ok',
code: 0,
token: 'sdfsdfsdfdsf',
data: { id: 1, username: 'kenny', sex: 6 }
})
} else {
return res.send({ status: 'error', code: 403 })
}
},
'DELETE /api/user/:id': (req, res) => {
console.log('---->', req.body)
console.log('---->', req.params.id)
res.send({ status: 'ok', message: '删除成功!' })
}
}
module.exports = proxy
上面定义了四个接口,每个接口的key都为请求方法和路径的组合字符串,value为json或者函数,表示返回结果。
- 在webpack.config.js中引入mocker-api
const apiMocker = require('mocker-api')
在devServer的before钩子中引入上述mocker.js
module.exports = {
....
devServer: {
before (app) {
apiMocker(app, path.resolve('./mock/mocker.js'))
}
}
....
}
- 使用
在代码中直接像请求后端接口一样对mock数据进行请求即可。
fetch('/api/user').then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
参考文档:
Webpack最简单的方式Mock API https://segmentfault.com/a/1190000013220134