如何在一个块中获取响应正文和响应标头

Asn*_*tta 5 reactjs react-native

我是 react-native 的新手我正在向服务器发送请求并希望在同一块中获得响应和正文,以便我可以将这两个项目发送到另一个函数,我的 fetch 方法看起来像

send_request = (data) =>{
  url = BASE_URL + "some/url.json"
  fetch(url, {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      user: {
        email: data.email,
        full_name: data.name,
      }
    })
  }).then((response) => {
    //how can I get response body here so that I can call following method
    // this.use_response(responsebody, response.headers)
    return response.json()
  }).then((responseJson) => {
    // or how can I get response headers here so that I can call following fuction
    // this.use_response(responseJson, headers)
    return responseJson
  }).catch((error) => {
    console.log(error)
  });
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能同时使用两者,请提前谢谢!

Est*_*ask 6

response.headers是一个可用的对象,而request.json()是一个需要解决的承诺。

为了将它们放在一个地方,使用简单的 ES6 承诺,应该有嵌套的thens:

  ...
  .then((response) => {
    return response.json().then(responseJson => {
      this.use_response(responseJson, response.headers)
    });
  })
Run Code Online (Sandbox Code Playgroud)

或者多个值应该作为数组或对象一起通过链传递:

  ...
  .then((response) => {
    return Promise.all([response.json(), response.headers]);
  }).then(([responseJson, headers]) => {
    this.use_response(responseJson, headers)
  })
Run Code Online (Sandbox Code Playgroud)

或者由于 React 应用程序不限于 ES5/ES6 并且可以使用 Babel 支持的所有功能,async..await因此可以使用它自然地解决此类问题:

send_request = async (data) =>{
  url = BASE_URL + "some/url.json"
  const response = await fetch(url, {...})
  const responseJson = await response.json();
  this.use_response(responseJson, response.headers);
}
Run Code Online (Sandbox Code Playgroud)