react+mockjs+axios使用
import Mock from 'mockjs' const Random = Mock.Random Mock.setup({ timeout: '500', }) function createUsers() { let user = [] while (true) { user.push({ name: Random.first(), sex: Random.boolean(1, 1, true) ? 'male' : 'female', age: Random.integer(20, 50), }) if (user.length === 2) break } return user } const todos = [ { url: '/getUsers', type: 'get', response: () => { return Mock.mock({ 'users|3-5': createUsers(), }) }, }, { url: '/addUser', type: 'post', response: (data) => { return Mock.mock({ data, }) }, }, ] export default todos
import Mock from 'mockjs'; import todo from './todo' const mocks = [ ...todo ] for( const item of mocks) { Mock.mock(item.url, item.type, item.response) }
import axios from 'axios' export const GET_TODO_URL = '/todo' const instance = axios.create({ baseURL: '/', timeout: 1000, }) instance.interceptors.request.use( function (config) { console.log(config) return config }, function (error) { return Promise.reject(error) }, ) instance.interceptors.request.use( function (response) { return response }, function (error) { return Promise.reject(error) }, ) export default instance
import request from './../../utils/request' export function getTodoApi() { return request({ url: '/getUsers', method: 'get', }) } export function editTodoApi(data) { return request({ url: '/addUser', method: 'post', data, }) }
// 引入mock import './mock/index'
import { getTodoApi } from '../../api/user' const getTodoInfo = async () => { const res = await getTodoApi() console.log(res) } useEffect(() => { getTodoInfo() // 调用 return () => {} }, [])
文章目录
关闭
共有 0 条评论