当我们获取时触发哪个事件

时间:2019-05-14 18:04:41

标签: javascript javascript-events fetch

我需要在UI上生成的所有XHR请求中添加标头。在整个页面上,我正在使用访存API。我需要在获取开始之前添加标题的方法,因此问题是,有什么方法可以在获取发生之前更改请求?

我知道获取事件,但仅适用于服务人员,而不能在实际的HTML页面上使用。

1 个答案:

答案 0 :(得分:0)

您需要一个拦截器。您可以使用:

https://github.com/werk85/fetch-intercept

然后:

import fetchIntercept from 'fetch-intercept';

const unregister = fetchIntercept.register({
    request: function (url, config) {
        // Modify headers here
        return [url, config];
    },

    requestError: function (error) {
        // Called when an error occured during another 'request' interceptor call
        return Promise.reject(error);
    },

    response: function (response) {
        // Modify the reponse object
        return response;
    },

    responseError: function (error) {
        // Handle an fetch error
        return Promise.reject(error);
    }
});

// Call fetch to see your interceptors in action.
fetch('http://google.com');

// Unregister your interceptor
unregister();