为每个fetch()请求设置默认标头

eRo*_*odY 23 authorization express reactjs redux fetch-api

是否可以使用fetch API为每个请求设置默认标头?
我想要做的是Authorization每当有一个json web令牌时设置一个标题localStorage.我目前的解决方案是使用此功能设置标头:

export default function setHeaders(headers) {
    if(localStorage.jwt) {
        return {
            ...headers,
            'Authorization': `Bearer ${localStorage.jwt}`
        }
    } else {
        return headers;
    }
}
Run Code Online (Sandbox Code Playgroud)

在获取请求中设置标题将如下所示:

return fetch('/someurl', {
        method: 'post',
        body: JSON.stringify(data),
        headers: setHeaders({
            'Content-Type': 'application/json'
        })
    })
Run Code Online (Sandbox Code Playgroud)

但必须有更好的方法来做到这一点.我正在开发一个React/Redux/Express应用程序,如果有任何帮助的话.

小智 21

创建fetch包装器可以解决您的问题:

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));
}
Run Code Online (Sandbox Code Playgroud)

如果您决定更喜欢 Axios 或其他软件包,您还可以获得额外的好处,即可以轻松地为应用程序中的所有调用切换请求客户端。你可以做其他事情,比如检查是否options.body是一个对象并添加'Content-Type: application/json标题。


小智 6

您可以使用Axios而不是使用拦截器获取

const setAuthorization = (token) => {

  api.interceptors.request.use((config) => {
    config.headers.Authorization = 'Bearer ' + token;
    return config;
  });

}
Run Code Online (Sandbox Code Playgroud)

其中Api是具有基本URL的axios对象

const api= axios.create({
  baseURL: 'http://exemple.com'
});
Run Code Online (Sandbox Code Playgroud)

当你得到你的令牌时,你只需要调用函数setAuthorization.

资料来源:Axios README.md

  • 您可以使用 axios 设置授权标头,然后使用普通的提取请求,标头也会为提取请求设置。 (2认同)

Nan*_*hop 6

有人创建fetch mixin以将set default设置为fetch.

https://github.com/moll/js-fetch-defaults


iur*_*niz 5

您可以覆盖默认的 fetch api:

\n
var originalFetch = window.fetch;\nwindow.fetch = function (input, init) {\n    if (!init) {\n        init = {};\n    }\n    if (!init.headers) {\n        init.headers = new Headers();\n    }\n\n    // init.headers could be: \n    //   `A Headers object, an object literal, \n    //    or an array of two-item arrays to set request\xe2\x80\x99s headers.`\n    if (init.headers instanceof Headers) {\n        init.headers.append(\'MyHeader\', \'Value\');\n    } else if (init.headers instanceof Array) {\n        init.headers.push([\'MyHeader\', \'Value\']);\n    } else {\n        // object ?\n        init.headers[\'MyHeader\'] = \'Value\';\n    }\n    return originalFetch(input, init);\n};\n
Run Code Online (Sandbox Code Playgroud)\n

参考:

\n\n