使用React.js在Redux中获取响应头对象

时间:2019-08-02 22:33:48

标签: javascript reactjs api github redux

使用React.js中的redux,我在过去30天内获得了最多加星标的存储库,现在我想使用github api提供的分页,但是要做到这一点,我必须在响应中使用标头,如何做到,如何更改代码以从响应中获取标头,这是获取响应的函数:

import getDate from './getDate';

export function fetchRepos() {
  return function(dispatch) {
    dispatch({
      type: "FETCH_REPOS_REQUEST",
    });

    return fetch(
      "https://api.github.com/search/repositories?q=created:>" + 
      getDate() + 
      "&sort=stars&order=desc",
    )
    .then(response => response.json().then(body => ({response, body})))
    .then(({response, body}) => {
      if (!response.ok) {
        dispatch({
          type: "FETCH_REPOS_FAILURE",
          error: body.error,
        });
      } else {
        dispatch({
          type: "FETCH_REPOS_SUCCESS",
          repos: body.items,
        });
      }
    });
  };
}

请帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

我喜欢组装一个包含标题的响应对象,以作为获取调用的对象,例如:

fetch('https://jsonplaceholder.typicode.com/users')
	.then(res => (res.headers.get('content-type').includes('json') ? res.json() : res.text())
	.then(data => ({
		headers: [...res.headers].reduce((acc, header) => {
			return {...acc, [header[0]]: header[1]};
		}, {}),
		status: res.status,
		data: data,
	}))
	.then(response => console.log(response)));

根据您的情况,您可以简单地在最后一个response.headers中获得带有.then()的标题。

但是从技术上讲,您可以使用res.headers.get('<header.name>')访问标头。