-
npm搜索:vite-plugin-mock
-
安装:npm install vite-plugin-mock mockjs -D
-
配置 vite.config.ts
import { viteMockServe } from 'vite-plugin-mock';
plugins: [
vue(),
viteMockServe({
enable: command === 'serve', // 是否使用mock接口;等于serve是开发阶段使用mock接口
}),
],
- 根目录创建 mock/user.ts,和node_moudules同级;
function createUserList() {
return [
{
userId: 1,
avatar: '',
username: 'admin',
password: '123456',
desc: '平台管理员',
roles: ['平台管理员'],
buttons: ['curser.detail'],
routes: ['home'],
token: 'Admin Token',
},
{
userId: 2,
avatar: '',
username: 'system',
password: '123456',
desc: '系统管理员',
roles: ['系统管理员'],
buttons: ['curser.detail', 'curser.user'],
routes: ['home'],
token: 'System Token',
},
];
}
export default [
{
url: '/api/user/login',
method: 'post',
timeout: 2000,
response: ({ body }) => {
const { username, password } = body;
const hasUser = createUserList().find(
(item) =>
item.username === username && item.password === password,
);
if (!hasUser) {
return { code: 201, data: { message: '账号或密码错误' } };
}
const { token } = hasUser;
return { code: 200, data: { token, message: '登录成功' } };
},
},
{
url: '/api/user/info',
method: 'get',
response: (request) => {
const token = request.headers.token;
const hasUser = createUserList().find(
(item) => item.token === token,
);
if (!hasUser) {
return { code: 201, data: { message: '获取用户信息失败' } };
}
return {
code: 200,
data: { hasUser, message: '获取用户信息成功' },
};
},
},
];
- 在项目中测试是否连接mock接口
import axios from 'axios';
axios({
url: '/api/user/login',
method: 'post',
data: {
username: 'admin',
password: '123456',
},
});
网友评论