Reactjs 如何在react js中为所有请求只创建一个服务层?

Reactjs 如何在react js中为所有请求只创建一个服务层?,reactjs,axios,redux-thunk,Reactjs,Axios,Redux Thunk,我想创建一个通用服务层来处理reactjs中的所有请求 以下是我迄今为止完成的代码: 这是一个thunk操作,服务层将从该操作开始。postRequest方法获取调用api所需的所有参数 bankCustomerThunkAction.js export const fetchBankCustomers = (filterType, searchParam) => dispatch => { apiServices.postRequest(urlBuilders.getUrl

我想创建一个通用服务层来处理reactjs中的所有请求

以下是我迄今为止完成的代码:

这是一个thunk操作,服务层将从该操作开始。postRequest方法获取调用api所需的所有参数

bankCustomerThunkAction.js

    export const fetchBankCustomers = (filterType, searchParam) => dispatch => {
apiServices.postRequest(urlBuilders.getUrlAppenderWithParams(bankCustomerApiConstant.GET_BANK_CUSTOMER_STATISTICS, "filter", filterType), searchParam).then((response) => dispatch(actions.getBankCustomerStatisticsWithDate(response))).catch(error => console.log("error", error))
dataService.bankCustomerThunkAction().then().catch()
}

这是唯一一个请求后端api的服务层

service.js

 export const postRequest = (url, data) => Axios({method: 'POST' , url:url , data : data})

这样做就足够了,还是有其他选择?

我想你这样做是对的

我可以给你一点建议,当你需要为一个特定的请求提供不同的标题时,这会有所帮助

就是

BankCustomerTunkAction.js->DataService.js->service.js

 export const postRequest = (url, data) => Axios({method: 'POST' , url:url , data : data})
bankCustomerThunkAction.js

    export const fetchBankCustomers = (filterType, searchParam) => dispatch => {
apiServices.postRequest(urlBuilders.getUrlAppenderWithParams(bankCustomerApiConstant.GET_BANK_CUSTOMER_STATISTICS, "filter", filterType), searchParam).then((response) => dispatch(actions.getBankCustomerStatisticsWithDate(response))).catch(error => console.log("error", error))
dataService.bankCustomerThunkAction().then().catch()
DataService.js->在这里您可以选择头代码或任何可选参数代码

export bankCustomerThunkAction ()=>apiServices.postRequest(urlBuilders.getUrlAppenderWithParams(bankCustomerApiConstant.GET_BANK_CUSTOMER_STATISTICS, "filter", filterType), searchParam).then((response) => dispatch(actions.getBankCustomerStatisticsWithDate(response))).catch(error => console.log("error", error))

这完全取决于您的用例,您可能希望将用户令牌添加到本地存储或Cookie的头中。因为我使用的是axios,所以我可以将头添加到它并使其成为全局常量dashboardAxiosInstance=axios。创建({baseURL:''});谢谢你的帮助我不能,因为我只有8个名声哦,没关系!