安装
npm install msw --save-dev
# or
yarn add msw --dev
创建mock文件
import { setupWorker } from 'msw'
import { handlers } from './handlers'
export const worker = setupWorker(...handlers)
import { rest } from 'msw'
export const handlers = [
rest.post('/login', (req, res, ctx) => {
sessionStorage.setItem('is-authenticated', 'true')
return res(
ctx.status(200),
)
}),
rest.get('/user', (req, res, ctx) => {
const isAuthenticated = sessionStorage.getItem('is-authenticated')
if (!isAuthenticated) {
return res(
ctx.status(403),
ctx.json({
errorMessage: 'Not authorized',
}),
)
}
return res(
ctx.status(200),
ctx.json({
username: 'admin',
}),
)
}),
]
初始化
npx msw init public/ --save
node中使用参考文档
Mock Service Worker