Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - fetch-intercept modify all headers

What is the proper way to intercept all requests and add headers using react with fetch-intercept? I have a config file that contains the call to fetchIntercept.register(). I have separate files for component api calls that import the fetchIntercept config file. I added the unregister() call after the api is called but the headers are not being added.

api/config.js

import fetchIntercept from 'fetch-intercept';

const unregister = fetchIntercept.register({
    request: function (url, config) {
        // Modify the url or config here
        const withDefaults = Object.assign({}, config);
        withDefaults.headers = defaults.headers || new Headers({
          'AUTHORIZATION': `Bearer ${JSON.parse(sessionStorage.credentials).authToken}`
        });
        return [url, withDefaults];
    },

    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);
    }
});

export default unregister;

api/packageApi.js

import unregister from '../api/config';

class PackageApi {

  static getAllPackages() {
    const request = new Request('/get/my/packages', {
      method: 'GET'
    });
    return fetch(request).then(response => {
      return response.json();
    }).catch(error => {
      return error;
    });
  }

}
unregister();

export default PackageApi;
like image 397
neridaj Avatar asked Jan 10 '18 20:01

neridaj


1 Answers

I adding the working example for the fetch-intercept in separate file, its works for me perfectly.

https://stackblitz.com/edit/react-fetch-intercept-bi55pf?file=src/App.js

App.js

import React from 'react';
import './style.css';
import { AuthInterceptor } from './AuthInterceptor';

export default class App extends React.Component {
  componentDidMount() {
    AuthInterceptor();
    fetch('http://google.com', {
      headers: {
        'Content-type': 'application/json',
      },
    });
  }
  render() {
    return (
      <div>
        <h1>Hello StackBlitz!</h1>
        <p>Start editing to see some magic happen :)</p>
      </div>
    );
  }
}

AuthInterceptor.js

import fetchIntercept from 'fetch-intercept';

export const AuthInterceptor = () => {
  fetchIntercept.register({
    request: function (url, config) {
      // Modify the url or config here
      config.headers.name = 'Aravindh';
      console.log(config);
      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);
    },
  });
};

You can see the updated header value in the console.

Thanks

like image 138
Jai Saravanan Avatar answered Oct 19 '22 05:10

Jai Saravanan