---
order: 7
title: 和服務端進行交互
type: 開發
---
Ant Design Pro 是一套基于 React 技術棧的單頁面應用,我們提供的是前端代碼和本地模擬數據的開發模式,通過 API 的形式和任何技術棧的服務端應用一起工作。下面將簡單介紹和服務端交互的基本寫法。
## 前端請求流程
在 Ant Design Pro 中,一個完整的前端 UI 交互到服務端處理流程是這樣的:
1. UI 組件交互操作;
2. 調用 model 的 effect;
3. 調用統一管理的 service 請求函數;
4. 使用封裝的 request.ts 發送請求;
5. 獲取服務端返回;
6. 然后調用 reducer 改變 state;
7. 更新 model。
從上面的流程可以看出,為了方便管理維護,統一的請求處理都放在 `services` 文件夾中,并且一般按照 model 維度進行拆分文件,如:
```
services/
user.ts
api.ts
...
```
其中,`utils/request.ts` 是基于 [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) 的封裝,便于統一處理 POST,GET 等請求參數,請求頭,以及錯誤提示信息等。具體可以參看 [request.ts](https://github.com/ant-design/ant-design-pro/blob/master/src/utils/request.ts)。
例如在 services 中的一個請求用戶信息的例子:
```ts
// services/user.ts
import request from '../utils/request';
export async function query() {
return request('/api/users');
}
export async function queryCurrent() {
return request('/api/currentUser');
}
// models/user.ts
import { queryCurrent } from '../services/user';
...
effects: {
*fetch({ payload }, { call, put }) {
...
const response = yield call(queryCurrent);
...
},
}
```
### 處理異步請求
在處理復雜的異步請求的時候,很容易讓邏輯混亂,陷入嵌套陷阱,所以 Ant Design Pro 的底層基礎框架 [dva](https://github.com/dvajs/dva) 使用 `effect` 的方式來管理同步化異步請求:
```js
effects: {
*fetch({ payload }, { call, put }) {
yield put({
type: 'changeLoading',
payload: true,
});
// 異步請求 1
const response = yield call(queryFakeList, payload);
yield put({
type: 'save',
payload: response,
});
// 異步請求 2
const response2 = yield call(queryFakeList2, payload);
yield put({
type: 'save2',
payload: response2,
});
yield put({
type: 'changeLoading',
payload: false,
});
},
},
```
通過 [generator](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Statements/function*) 和 [yield](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Operators/yield) 使得異步調用的邏輯處理跟同步一樣,更多可參看 [dva async logic](https://github.com/dvajs/dva/blob/master/docs/GettingStarted.md#async-logic)。