首先安裝我們所需要的庫鞠评,axios,mock壕鹉,mock-api剃幌。
npm install axios
npm install mockjs
npm install mocker-api
然后在我們的src文件夾下新建mock文件夾,在mock文件夾下創(chuàng)建moker.js用來存放模擬的接口數(shù)據(jù)晾浴。具體內(nèi)容如下:
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;
然后需要在webpackDevServer.config.js文件中配置mock相關(guān)庫(如果沒有暴露配置文件,需要通過npm run eject命令先暴露出配置文件)
......
const path = require('path');
......
//mock模塊引入
const apiMocker = require('mocker-api');
.......
before(app, server) {
......
? ? ? //mocker模擬后端接口
? ? ? apiMocker(app, path.resolve(__dirname, '../src/mock/mocker.js'));
......
}
最后就可以在我們所需要使用mock的地方直接模擬接口調(diào)用了.
getData = () => {
? ? axios.get('/api/user')
? ? .then(res => {
? ? console.log(res.data);
? ? })
? ? .catch(err => {
? ? console.log(err);
? ? });
? }