Reputation: 2183
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;
Upvotes: 9
Views: 14614
Reputation: 443
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
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>
);
}
}
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
Upvotes: 6
Reputation: 2513
The use of unregister seems incorrect. You have unregistered before any calls are made.
Upvotes: 0