最近学习vue,需要后台模拟数据,从npm中搜索到axios-mock-adapter,即axios的模拟调试器,通过axios模拟调用后台,后台数据可以使用mock.js来造假数据。现将研究的做如下记录:
npm包链接
1.安装
1.1 npm方式
npm install axios-mock-adapter --save-dev
1.2 script引入方式
<script src="https://unpkg.com/axios-mock-adapter/dist/axios-mock-adapter.js"></script>
<script src="https://unpkg.com/axios-mock-adapter/dist/axios-mock-adapter.min.js"></script>
2.引入
2.1 es6 引入方式 import
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
2.2 require 引入方式
var axios = require('axios');
var MockAdapter = require('axios-mock-adapter');
3.使用 example
首先创建一个实例
let mock = new MockAdapter(axios);
3.1模拟一个GET请求 ES6
//导入模块
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
// 设置模拟调试器实例
var mock = new MockAdapter(axios);
// 模拟任意GET请求到 /users
//reply的参数为 (status, data, headers)
mock.onGet('/users').reply(200, {
users: [
{ id: 1, name: 'John Smith' }
]
});
axios.get('/users')
.then(function(response) {
console.log(response.data);
});
3.2 模拟一个GET请求带参数的parameters
mock.onGet('/users', { params: { searchText: 'John' } }).reply(200, {
users: [
{ id: 1, name: 'John Smith' }
]
});
axios.get('/users', { params: { searchText: 'John' } } )
.then(function(response) {
console.log(response.data);
});
//在初始化模拟调试器的时候,设置几秒的延迟:响应的延迟
var mock = new MockAdapter(axiosInstance, { delayResponse: 2000 });
3.3 传递一个function to reply
mock.onGet('/users').reply(function(config) {
//config是axios config
//返回一个数组[status, data, headers]
return [200, {
users: [
{ id: 1, name: 'John Smith' }
]
}];
});
3.4 没有具体路径的时候
// 拒绝所有的 POST 请求,返回 HTTP 500
mock.onPost().reply(500);
3.5 模拟一个put请求 body/data
mock.onPut('/product', { id: 4, name: 'foo' }).reply(204);
4.实例
let mock = new MockAdapter(axios);
// 模拟成功请求
mock.onGet('/success').reply(200, {
msg: 'success'
});
// 模拟错误请求
mock.onGet('/error').reply(500, {
msg: 'failure'
});
//模拟登录 POST
mock.onPost('/login').reply(config => {
let {username, password} = JSON.parse(config.data);
return new Promise((resolve, reject) => {
let user = null;
setTimeout(() => {
let hasUser = LoginUsers.some(u => {
if (u.username === username && u.password === password) {
user = JSON.parse(JSON.stringify(u));
user.password = undefined;
return true;
}
});
if (hasUser) {
resolve([200, { code: 200, msg: '请求成功', user }]);
} else {
resolve([200, { code: 500, msg: '账号或密码错误' }]);
}
}, 1000);
});
});
axios.post('/login', params).then(res => res.data);
//模拟批量删除 GET
mock.onGet('/user/batchremove').reply(config => {
let { ids } = config.params;
ids = ids.split(',');
***_Users = _Users.filter(u => !ids.includes(u.id));***
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve([200, {
code: 200,
msg: '删除成功'
}]);
}, 500);
});
});
axios.get(`${base}/user/batchremove`, { params: params });
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。