我有一个示例代码:
api.get("myUrl")
.then((response)=>{
console.log(response)
if(response.ok && response.status == 200){
//displaying data to screen
} else{
//display alert failed to call API
}
})现在,我想处理我想要重定向到login page的authorization token is failed,但我不想将代码authorization token is failed添加到我的所有api请求
是否有一种方法可以只创建一次代码else if(!response.ok && response.status == 401){redirectToLogin()},而不是将这些代码添加到我的所有API.get中
发布于 2019-01-28 19:04:49
对于我们的react原生应用程序,我使用自己的get、delete、put、update方法创建了一个类,用于处理错误,然后调用apisauce.get e.t.c。
我使用流类型注释,但使用typescript会更好,因为它可以轻松地创建私有方法。
type ApiRequest = (url: string, payload?: Object) => Promise<ApiResponse>;
export class Api {
apiSauce: {
get: ApiRequest,
post: ApiRequest,
put: ApiRequest,
delete: ApiRequest,
};
constructor(baseURL: string) {
this.apiSauce = apisauce.create({
baseURL,
headers: {
"Cache-Control": "no-cache",
},
timeout: 60 * 1000,
});
}
_get = async (url: string, payload?: Object) => {
const res = await this._handleResponse(this.apiSauce.get, { url, payload });
return res;
};
_put = async (url: string, payload?: Object) => {
const res = await this._handleResponse(this.apiSauce.put, { url, payload });
return res;
};
_post = async (url: string, payload?: Object) => {
const res = await this._handleResponse(this.apiSauce.post, { url, payload });
return res;
};
_delete = async (url: string, payload?: Object) => {
const res = await this._handleResponse(this.apiSauce.delete, { url, payload });
return res;
};
_handleResponse = async (apiRequest: ApiRequest, params: ApiRequestParams): Promise<ApiResponse> => {
const res = await apiRequest(params.url, params.payload);
return this._handleError(res);
};
_handleError = (res: ApiResponse) => {
if (!res.ok) {
if (res.status === 401 || res.status === 403) {
// **redirect to login page**
}
if (res.data && res.data.message) {
showNotification(res.data.message);
}
showNotification(res.problem);
}
return res;
};
getUser = async (userId: string): Promise<User> => {
const response = await this._get(`users/{userId}`);
return transformUserApiResponse(response.data);
};
}
const MyApi = new Api(BASE_URL);https://stackoverflow.com/questions/52440280
复制相似问题