这几天折腾了Ant Design Pro,组件什么的都挺容易的。后来准备调用后台提供的接口。之前重来没接触过umi和dva,
调用接口时有些懵。看了一些umi和dva的文档之后再反过来看And Design Pro文档,折腾了好些时间才把这个问题解决,
在这里记录和分享一下,希望能帮到和我一样的同志。
1. 修改/config/config.js文件
export default {
proxy: {
"/testapi/" : {
"target" : "https://www.xxx.com/" ,
"changeOrigin" : true ,
pathRewrite: {
'^/testapi/' : '/api/api.php?request='
} ,
} ,
} ,
}
Ant Design Pro 内置了 umi,umi 使用了 webpack devServer来支持代理。 你只需要在 config.js 中配置 proxy 属性。只要 proxy 和 mock url 不同,是可以共存的。
2.调用接口
在/src/services/api.js
文件中创建一个异步方法并使用/src/utils/request.js
中的request
方法定义请求地址
import request from '@/utils/request' ;
export async function firstApi ( param) {
return request ( '/testapi/view_list' , {
method: "post" ,
body: {
... param,
}
} ) ;
}
request
方法第一个参数为请求地址,第二个为对象,定义请求方式或参数等。请求地址里的/testap/
则代理到第一步配置的proxy
对象中,如此一来完整的请求地址是:https://localhost:8000/testapi/view_list
,实际则是代理的:https://www.baidu.com/api/api.php?request=view_list
,只不过是将请求接口的url
中不需要改动的写到了proxy
对象中,经常需要修改的定义到了services
中
3创建model
在/src/models
文件夹中创建新的model文件。例如:bit.js
import { firstApi } from "../services/api" ;
export default {
namespace: 'mbit' ,
state: {
bit: [ ] ,
} ,
effects: {
* firstRequest ( { payload } , { call, put } ) {
const response = yield call ( firstApi, payload) ;
yield put ( {
type: "reMethod" ,
payload: Array. isArray ( response) ? response : [ ] ,
} ) ;
}
} ,
reducers: {
reMethod ( state, action) {
return {
... state,
bit: action. payload,
}
}
} ,
}
4.使用model
在/src/components/
中创建一个组件,在组件中创建连接,以model->bit.js为例
import styles from "./Bit.less" ;
import request from "@/utils/request" ;
import { connect } from 'dva' ;
@connect ( ( { mbit, loading } ) => ( {
mbit,
loading: loading. models. monitor,
} ) )
class Bit extends React. Component {
state = {
}
componentDidMount ( ) {
this . props. dispatch ( {
type: 'mbit/firstRequest' ,
payload: {
args1: "参数1" ,
args2: "参数2" ,
} ,
} ) ;
}
render ( ) {
const { bit } = this . props. mbit;
console. log ( bit ) ;
return (
< div> 测试请求< / div>
) ;
}
}
export default Bit;
需要注意的是,配置了proxy代理后。在浏览器中看到的所有Network请求将不会显示实际请求地址。