mock.js 的安装
npm install -D vite-plugin-mock mock.js
vite.config.ts配置:
import { viteMockServe } from 'vite-plugin-mock'
import { userConfigExport, ConfigEnv } from 'vite'
export default defineConfig(({ command }) => {
return {
plugins: [
viteMockServe({
localEnabled: command === 'serve'
})
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
}
})
接口模拟:
function createUserList(){
return [{
userId: 1,
userName: '张三',
password: '111111',
desc: '平台管理员',
roles: ['cuser.detail'],
routes: ['home'],
token: 'admin token'
},{
userId: 2,
userName: '李四',
password: '111111',
desc: '系统管理员',
roles: ['cuser.detail', 'cuser.user'],
routes: ['home'],
token: 'system token'
}]
}
export default [
// 登录
{
url: '/api/user/login',
method: 'post',
response: ({ body}) => {
const { userName, password } = body;
const checkUser = createUserList().find(
item => item.userName === userName && item.password === password
)
if(!checkUser){
return { code: 201, data: {message: '账号或密码不正确'}}
}
const { token } = checkUser
return { code: 200, data: { token }}
}
},
{
url: '/api/user/info',
method: 'get',
response: (request) => {
const token = request.headers.token;
const checkUser = createUserList().find(item => item.token === token)
if(!checkUser){
return { code:201, data: { message: '获取用户信息失败'}}
}
return { code: 200, data: { checkUser}}
}
}
]
接口调用:
axios({
url: '/api/user/login',
method: 'post',
data: {
userName: '张三',
password: '111111'
}
})
请求成功。