React教程(十五) : axios + mockjs
在后台接口还没准备好的时候,我们可能会需要模拟数据来支持前端开发。
继续使用之前的代码示例:https://github.com/992990831/modernization/tree/main/full-demo
npm install axios --save
npm install mockjs --save-dev
先添加一个REST API: http://localhost:5000/order
返回数据: [{"id":1,"note":"order number 1"},{"id":2,"note":"order number 2"},{"id":3,"note":"order number 3"},{"id":4,"note":"order number 4"},{"id":5,"note":"order number 5"},{"id":6,"note":"order number 6"},{"id":7,"note":"order number 7"},{"id":8,"note":"order number 8"},{"id":9,"note":"order number 9"}]
回到前端,添加Request.tsx文件,作为对axios的封装
import axios from 'axios';
export const Get_Order_Url = '/order';
export const Request = axios.create({
baseURL: 'http://localhost:5000/', //这个配置可以放到环境变量中,参见第一篇文章。
responseType: 'json'
});
// Add a request interceptor
Request.interceptors.request.use(function (config) {
// Do something before request is sent
debugger;
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
Request.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
debugger;
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
添加OrderService.tsx作为业务层的封装,代码如下:
import { Request, Get_Order_Url } from '../util/Request';
export interface Order{
id: number;
note: string;
}
class OrderService {
async getOrders(): Promise<Order[]> {
let success = false;
let orders:Order[] = [];
try {
orders = await Request.get(Get_Order_Url);
success=true;
} catch {
console.log('error when fetch order')
}
return success ? orders : Promise.reject();
}
}
export const orderService = new OrderService();
Orders.tsx做如下修改:
运行后的效果如下:
加入模拟数据,新建模拟数据文件:
import Mock from 'mockjs'
export default Mock.mock('http://localhost:5000/order','get',
[{"id":11,"note":`order number ${Mock.Random.id()}`},
{"id":12,"note":`order number ${Mock.Random.id()}`},
{"id":13,"note":`order number ${Mock.Random.id()}`},
{"id":4,"note":`order number ${Mock.Random.id()}`},
{"id":5,"note":`order number ${Mock.Random.id()}`},
{"id":6,"note":`order number ${Mock.Random.id()}`},
{"id":7,"note":"order number 7"},
{"id":8,"note":"order number 8"},
{"id":9,"note":"order number 9"}]
)
注意,mock方法里的url必须和axios中的url完全一致
不仅是path的部分,而是整个url。
在index.tsx中引入该mock数据
MockJS会自动拦截对应url的请求。
这里还有个问题,如果要取消模拟,必须手动把下面这行代码删除(在index.tsx中)
import './Mock/MockOrder';
一个简单的解决方案:动态导入Mock组件
process.env.NODE_ENV==='development' && require('./Mock/MockOrder');
通过上面的修改,只有在dev环境才会导入mock组件