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

问题描述 投票:3回答:2

我是新来的反应 - 本机我正在向服务器发送请求并希望得到响应和正文在同一个块,以便我可以将这两个项目发送到另一个函数我的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)
  });
}

如何同时使用两者请提前帮助谢谢!

reactjs react-native
2个回答
3
投票

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

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

  ...
  .then((response) => {
    return response.json().then(responseJson => {
      this.use_response(responseJson, response.headers)
    });
  })

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

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

或者由于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);
}

1
投票

我看到的最简单的方法是将标头发送到send_request函数,当你有响应时,将它们包装成一个对象并返回它们。

© www.soinside.com 2019 - 2024. All rights reserved.