拦截所有请求并使用fetch-intercept反应添加标头的正确方法是什么?我有一个配置文件,其中包含对fetchIntercept.register()的调用.我有用于导入fetchIntercept配置文件的组件api调用的单独文件.我在调用api之后添加了unregister()调用,但是没有添加标头.
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;
最佳答案 这很简单,使用axios而不是fetch.