【问题标题】:How to get response body and response headers in one block如何在一个块中获取响应正文和响应标头
【发布时间】:2018-09-10 15:29:52
【问题描述】:

我是 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)
  });
}

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

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2012-05-02
        • 2011-07-02
        • 1970-01-01
        • 1970-01-01
        • 2011-03-30
        • 1970-01-01
        • 2020-08-10
        • 2013-05-28
        • 2013-06-19
        相关资源
        最近更新 更多