1

I want to intercept all the AJAX calls in my app and am planning to use the below

axios.interceptors.request.use(req => {
  // `req` is the Axios request config, so you can modify
  // the `headers`.
  req.headers.someCustomHeader = 'XYZ';
  return req;
});

So basically, I want to set some custom header on all requests going out. But since in my app, I also have used fetch calls, not sure if the above would intercept only axios calls OR also intercept fetch() calls ?

copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • You can test this by seeing if the fetch calls contain that custom header. My bet is the fetch calls will not contain that header. – Gabriel Lupu Nov 05 '21 at 07:53
  • @GabrielLupu - yes, it does not contain that header...Not sure if there is a way to have one common intereceptor for both axios and fetch...That way, I have a common handling for both – copenndthagen Nov 05 '21 at 08:03
  • Did you try monkey patching `XMLHttpRequest` – Eldar Nov 05 '21 at 08:13
  • Nope....Any example for reference if you have? – copenndthagen Nov 05 '21 at 08:29
  • Check [this](https://stackoverflow.com/questions/16959359/intercept-xmlhttprequest-and-modify-responsetext) out. patch the open method and then call the setRequestHeaders method. – Eldar Nov 05 '21 at 08:40
  • Thanks...Seems like the example is for the response...I am looking to intercepting request... – copenndthagen Nov 05 '21 at 08:59
  • Well, it seems `fetch` itself should be monkey patched. [this](https://stackoverflow.com/questions/45425169/intercept-fetch-api-requests-and-responses-in-javascript) – Eldar Nov 05 '21 at 09:32

0 Answers0