从fetch()提取JSON和标头

ner*_*ist 2 javascript response response-headers fetch-api

我正在为一个简单的react / redux应用程序建模auth层。在服务器端,我有一个基于devise_token_auth gem 的API 。

fetch用来发布登录请求:

const JSON_HEADERS = new Headers({
  'Content-Type': 'application/json'
});

export const postLogin = ({ email, password }) => fetch(
  `${API_ROOT}/v1/auth/sign_in`, {
    method: 'POST',
    headers: JSON_HEADERS,
    body: JSON.stringify({ email, password })
});

// postLogin({ email: 'test@test.it', password: 'whatever' });
Run Code Online (Sandbox Code Playgroud)

这行得通,我得到200响应以及所需的所有数据。我的问题是,信息在响应正文和标头之间划分。

  • 正文:用户信息
  • 标头:访问令牌,有效期等

我可以这样解析JSON主体:

postLogin({ 'test@test.it', password: 'whatever' })
  .then(res => res.json())
  .then(resJson => dispatch(myAction(resJson))
Run Code Online (Sandbox Code Playgroud)

但是,这样myAction就不会从标头中获取任何数据(在解析JSON时丢失)。

有没有办法从fetch请求中获取标头和正文?谢谢!

ner*_*ist 6

我以为我会分享我们最终解决此问题的方式:通过在.then链中添加一个步骤(在解析JSON之前)来解析auth标头并调度适当的操作:

fetch('/some/url')
  .then(res => {
    const authHeaders = ['access-token', 'client', 'uid']
      .reduce((result, key) => {
        let val = res.headers.get(key);
        if (val) {
          result[key] = val;
        }
      }, {});
    store.dispatch(doSomethingWith(authHeaders)); // or localStorage
    return res;
  })
  .then(res => res.json())
  .then(jsonResponse => doSomethingElseWith(jsonResponse))
Run Code Online (Sandbox Code Playgroud)

另一种方法受到强大的Dan Abramov的启发(http://stackoverflow.com/a/37099629/1463770

fetch('/some/url')
  .then(res => res.json().then(json => ({
    headers: res.headers,
    status: res.status,
    json
  }))
.then({ headers, status, json } => goCrazyWith(headers, status, json));
Run Code Online (Sandbox Code Playgroud)

高温超导