首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >apisauce (axios包装器)-我是否可以处理响应错误以编写一次并自动调用,而不是在其他情况下手动添加

apisauce (axios包装器)-我是否可以处理响应错误以编写一次并自动调用,而不是在其他情况下手动添加
EN

Stack Overflow用户
提问于 2018-09-21 17:05:05
回答 1查看 4.5K关注 0票数 0

我有一个示例代码:

代码语言:javascript
复制
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 pageauthorization token is failed,但我不想将代码authorization token is failed添加到我的所有api请求

是否有一种方法可以只创建一次代码else if(!response.ok && response.status == 401){redirectToLogin()},而不是将这些代码添加到我的所有API.get

EN

回答 1

Stack Overflow用户

发布于 2019-01-28 19:04:49

对于我们的react原生应用程序,我使用自己的get、delete、put、update方法创建了一个类,用于处理错误,然后调用apisauce.get e.t.c。

我使用流类型注释,但使用typescript会更好,因为它可以轻松地创建私有方法。

代码语言:javascript
复制
 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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52440280

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档