Creating a fetch
wrapper could solve your problem:
function updateOptions(options) {
const update = { ...options };
if (localStorage.jwt) {
update.headers = {
...update.headers,
Authorization: `Bearer ${localStorage.jwt}`,
};
}
return update;
}
export default function fetcher(url, options) {
return fetch(url, updateOptions(options));
}
You also get the added benefit of being able to switch your request client easily for all the calls in your application if you decide you like Axios or other package better. And you can do other things like check if options.body
is an object and add the 'Content-Type: application/json
header.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…