數據格式
定義後端數據默認的返回格式如下:
interface ErrorInfoStructure {
success: boolean; // if request is success
data?: any; // response data
errorCode?: string; // code for errorType
errorMessage?: string; // message display to user
showType?: number; // error display type: 0 silent; 1 message.warn; 2 message.error; 4 notification; 9 page
traceId?: string; // Convenient for back-end Troubleshooting: unique request ID
host?: string; // onvenient for backend Troubleshooting: host of current access server
}
若您當前的返回數據不符合該規範,則需要進行主動調整。有兩處需要調整:
① 編譯時配置:(可配置數據字段)
在 config.ts 中配置
export default {
request: {
dataField: 'data',
},
};
② 運行時配置 (可配置是否錯誤及返回的錯誤信息字段) 在 src/app.ts 中配置
import { RequestConfig } from 'umi';
export const request: RequestConfig = {
errorConfig: {
adaptor: (resData) => {
return {
...resData,
success: resData.ok,
errorMessage: resData.message,
};
},
},
};
此外,還有中間層、攔截器,可參考具體的文檔
useRequest
差異
相比 @umijs/use-request 本身,有如下兩點差異:
- 按照接口請求規範內置了 formatResult: res => res?.data 讓你可以更方便的使用數據,當然你也可以自己配置 formatResult 來覆蓋內置的這個邏輯。
- 按照接口錯誤規範統一了錯誤處理邏輯。
request
差異 相比於 umi-request,一個不同的是 options 擴展了一個配置 skipErrorHandler,該配置爲 true 是會跳過默認的錯誤處理,用於項目中部分特殊的接口。
request('/api/user', {
params: {
name: 1,
},
skipErrorHandler: true,
})