使用fetch API,是否可以为每个请求设置默认标头?
我的想法是在localStorage
中有JSON Web Token时设置Authorization
标头。 我当前的解决方案是使用此函数设置标头:
export default function setHeaders(headers) {
if(localStorage.jwt) {
return {
...headers,
'Authorization': `Bearer ${localStorage.jwt}`
}
} else {
return headers;
}
}
在fetch请求中设置headers,代码如下:
return fetch('/someurl', {
method: 'post',
body: JSON.stringify(data),
headers: setHeaders({
'Content-Type': 'application/json'
})
})
但是肯定有更好的方法来做这件事。如果可以的话,我目前正在开发一个React/Redux/Express应用程序。