gpt4 book ai didi

javascript - 从 fetch() 中提取 JSON 和 header

转载 作者:行者123 更新时间:2023-11-29 16:06:11 25 4
gpt4 key购买 nike

我正在为一个简单的 React/Redux 应用程序的身份验证层建模。在服务器端,我有一个基于 devise_token_auth 的 API gem 。

我正在使用 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' });

这有效,我得到了 200 响应和我需要的所有数据。我的问题是,信息在响应正文和 header 之间划分。

  • 正文:用户信息
  • header :访问 token 、到期时间等。

我可以这样解析 JSON 主体:

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

但是 myAction 不会从 header 中获取任何数据(在解析 JSON 时丢失)。

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

最佳答案

我想我会分享我们最终解决这个问题的方法:只需在 .then 链中添加一个步骤(在解析 JSON 之前)来解析 auth header 并分派(dispatch)适当的操作:

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))

另一种方法,灵感来自强大的 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));

HTH

关于javascript - 从 fetch() 中提取 JSON 和 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41812056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com