-1

I need to add a header in all XHR request generating on UI. On entire page I am using fetch api. I need way to add a header just before fetch start, hence the question , is there any way I can change request before fetch happens?

I know Fetch Event but that works only with service workers not on actual HTML page.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Akshay Garg
  • 80
  • 1
  • 3
  • `Fetch` is not an event, it's a method that belongs to an API which accepts an argument where headers (and other additional parameters) can be injected: https://developer.mozilla.org/it/docs/Web/API/Fetch_API/Using_Fetch Can you please show how you actually are using `Fetch`? – briosheje May 14 '19 at 18:06
  • I know fetch isn’t a event. Question is can I intercept fetch call ? – Akshay Garg May 15 '19 at 11:45
  • You can probably use `apply` on the original fetch method, as explained here: https://stackoverflow.com/questions/45425169/intercept-fetch-api-responses-and-request-in-javascript – briosheje May 15 '19 at 11:50

1 Answers1

0

You need a interceptor. You can use:

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

And then:

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();
German Burgardt
  • 375
  • 1
  • 5
  • IE doesn’t support fetch so I am using a poly fill for that. I don’t think this interceptor will work with that. Is there any way I can achieve same functionality without Amy external library – Akshay Garg May 15 '19 at 11:44