1. Mock 数据的方式

2. json-server 实现 Mock 数据
- 项目中安装 json-server
npm i -D json-server - 准备一个 json 文件
- 添加启动命令
//package.json
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"server": "json-server ./server/data.json --port 8888"
},
- 执行我们自己添加的命令即可开启mock服务


3. vite 项目中使用 mock
方法一
安装依赖: https://www.npmjs.com/package/vite-plugin-mock
// pnpm install -D vite-plugin-mock mockjs
// 以下为我的安装:
pnpm install -D mockjs
pnpm install vite-plugin-mock@2.9.8 -D
在 vite.config.js 配置文件启用插件。
import { UserConfigExport, ConfigEnv } from 'vite'
import { viteMockServe } from 'vite-plugin-mock'
import vue from '@vitejs/plugin-vue'
export default ({ command })=> {
return {
plugins: [
vue(),
viteMockServe({
localEnabled: command === 'serve',
}),
],
}
}
在根目录创建mock文件夹:去创建我们需要mock数据与接口!!!
在mock文件夹内部创建一个user.ts文件
//用户信息数据
function createUserList() {
return [
{
userId: 1,
avatar:
'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
username: 'admin',
password: '111111',
desc: '平台管理员',
roles: ['平台管理员'],
buttons: ['cuser.detail'],
routes: ['home'],
token: 'Admin Token',
},
{
userId: 2,
avatar:
'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
username: 'system',
password: '111111',
desc: '系统管理员',
roles: ['系统管理员'],
buttons: ['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) => {
//获取请求头携带token
const token = request.headers.token;
//查看用户信息是否包含有次token用户
const checkUser = createUserList().find((item) => item.token === token)
//没有返回失败的信息
if (!checkUser) {
return { code: 201, data: { message: '获取用户信息失败' } }
}
//如果有返回成功信息
return { code: 200, data: {checkUser} }
},
},
]
安装axios
pnpm install axios
最后通过axios测试接口。
方法二
安装网络请求库:
npm i axios
安装 mock 和在 vite 中使用 mock 的关联插件:
npm i mockjs vite-plugin-mock
添加配置 vite.config.js:

在目录 mock 下创建若干假数据文件,我这里以 user 为例:

user.js
export default [
{
url: '/api/user/info', // 接口路径
method: 'GET', // 请求方法
response: () => { // 返回响应
return {
code: 0,
message: '请求成功',
data: {
id: 1,
name: 'xiu',
goal: '用追马的时间去种草,马自然就来了。'
}
}
}
}
]
在需要数据的页面做接口请求,我这里以 App.vue 为例:
const getInfo = async () => {
const result = await axios.get('/api/user/info')
console.log(result)
}
onMounted(() => {
getInfo()
})
然后就可以实现假接口数据请求啦~

4. cra(Webpack) 中使用 Mockjs
npm install mockjs
src/_mock/index.js
Mock.mock('/api/test', 'get', () => {
return {
code: 200,
data: {
name: 'test'
},
message: 'success'
}
})
然后在需要使用 mock 的组件中直接引入 mock文件
import '../_mock/index.js'
//...
useEffect(() => {
axios('/api/test').then(res => res.json()).then( data => consoel.log(data))
}, [])
注意不能使用 fetch,因为 Mockjs 底层使用的 是 xhr(axios)。

2653

被折叠的 条评论
为什么被折叠?



