在不同的文件/功能中捕获axios请求 [英] Catch axios requests in different files / functions

查看:146
本文介绍了在不同的文件/功能中捕获axios请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用HTTP请求来获取Vue.js应用程序的数据。我有一个名为 Api.js 的文件,带有基本axios实例:

I use HTTP requests to get data for my Vue.js application. I have one file called Api.js with the base axios instance:

export default () => {
  return axios.create({
    baseURL: apiURL,
    headers: {
      Authorization: `JWT ${store.state.token}`
    }
  })
}

比我有一个名为 service.js的文件,其中包含不同端点的功能:

than I have a file called service.js, which contains the functions for the different endpoints:

export default {
  status() {
    return Api().get('status/')
  }
}

.vue 文件中,我这样调用该方法。

In the .vue file I call the method like that.

created() {
  Service.status()
    .then(response => {
      // do something with the data
    })
    .catch(e => {
      // show exception
    })
}

有些异常应在 Api.js 中处理(例如:401),其他一些异常应在 service.js 中处理,而其他异常应在 .vue中处理文件。我该怎么做?

Some exceptions should be handled in Api.js (for example: 401), some other exceptions should be handled in service.js and others in the .vue file. How can I do that?

推荐答案

免责声明:我创建了两个小的axios插件来轻松实现此特定模式。


简单的axios HTTP中间件服务可简化对通过Axios发出的HTTP请求的挂钩。

Simple axios HTTP middleware service to simplify hooking to HTTP requests made through Axios.

它使用axios拦截器作为acdcjunior提到的 在常见的中间件模式下使用axios,因此您的应用无需知道并处理拦截器语法。

It uses axios interceptors as mentioned by acdcjunior but it abstracts the use of axios with a commonly known middleware pattern so your app doesn't need to know and deal with the interceptor syntax.

// import your API's axios instance
import http from './api';
import { Service } from 'axios-middleware';

// Create a new service instance
const service = new Service(http);

// We're good to go!
export default service;

然后您可以使用此中间件服务在应用程序中的任何位置注册不同的中间件。中间件可以像对象一样简单,也可以是可重用,易于测试的类。

You can then use this middleware service to register different middlewares anywhere in your app. A middleware can be as simple as an object or a reusable, easily testable class.

import i18n from './services/i18n';
import toast from './services/toast';
import service from './services/middleware';
import { ApiErrorMiddleware, OtherMiddleware } from './middlewares';


// Then register your middleware instances.
service.register([
    // Middleware class instance
    new ApiErrorMiddleware(i18n, toast),
    new OtherMiddleware(),
    // or a simple object
    {
        onRequest() {
            // handle the request
        },
        onResponseError(error) {
            // handle the response error
        }
    }
]);

其中 ApiErrorMiddleware 是一个简单的类

export default class ApiErrorMiddleware {
    /**
     * @param {VueI18n} i18n instance
     * @param {Object} toast message service
     */
    constructor(i18n, toast) {
        this.toast = toast;
        this.i18n = i18n;
    }

    /**
     * @param {Object} error
     */
    onResponseError(error = {}) {
        const { response } = error;
        let key = 'errors.default';

        if (response && this.i18n.te(`errors.${response.status}`)) {
            key = `errors.${response.status}`;
        } else if (error.message === 'Network Error') {
            key = 'errors.network-error';
        } else {
            // TODO log unhandled errors
        }
        this.toast.error(this.i18n.t(key));
    }
}



axios资源



axios-resource


简单的axios资源

Simple axios resource class to easily interact with a REST endpoint.

定义资源类。在这里,我添加了 onError onFetchError 作为您的用例示例。

Define a resource class. Here, I added onError and onFetchError as examples for your use-case.

import Resource from 'axios-resource';

export default class UserResource extends Resource {
    static URL = 'user/{id}';

    // This calls `sync` in the background
    fetch() {
        return super.fetch.apply(this, arguments)
            .catch(err => this.onFetchError(err));
    }

    onFetchError(err) {
        // An error occurred while fetching this resource.
    }

    onError(err) {
        // An error occurred with this resource
    }

    // called for every actions (fetch, create, patch, delete)
    sync() {
        return super.sync.apply(this, arguments)
            .catch((err) => this.onError(err))
    }
}

然后,在 api中.js ,创建一个实例。

Then, in api.js, create an instance.

import UserResource from './user';

const user = new UserResource();

// GET https://example.com/api/user/me
user.fetch('me')
    .then(({ data }) => {
        console.log('User data:', data);
    });

可以在每一步处理错误。

The error can be dealt with at every step.


  1. 中的
  2. 资源的onError

  3. 在应用的中间件中。

这篇关于在不同的文件/功能中捕获axios请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆