【问题标题】:How to get response header in react native android?如何在反应原生android中获取响应标头?
【发布时间】:2016-06-29 08:23:05
【问题描述】:

您好,我想在获取 POST 请求后获取响应标头。我尝试调试以查看 responseconsole.log(response) 内部的内容。我可以从responseData 获取响应正文,但我不知道如何获取标题。我想同时获得标题和正文。请帮忙。谢谢:)

这是我所做的示例:

   fetch(URL_REGISTER, {
      method: 'POST',
      body: formData
    })
      .then((response) => response.json())
      .then((responseData) => {
        if(responseData.success == 1){
          this.setState({
            message1: responseData.msg,
          });
        }
        else{
          this.setState({
            message1: responseData.msg,
          });
        }
      })
      .done();
    }, 

【问题讨论】:

    标签: javascript android xmlhttprequest react-native response


    【解决方案1】:

    你可以这样做

      fetchData() {
      var URL_REGISTER = 'https://www.example.com';
      fetch(URL_REGISTER, {method: 'POST',body: formData})
          .then(
              function(response) {
                  console.log(response.headers.get('Content-Type'));
                  console.log(response.headers.get('Date'));
    
                  console.log(response.status);
                  console.log(response.statusText);
                  console.log(response.type);
                  console.log(response.url);
                  if (response.status !== 200) {
                      console.log('Status Code: ' + response.status);
                      return;
                  }
    
                  // Examine the text in the response
                  response.json().then(function(data) {
                      console.log(data);
                  });
              }
          )
          .catch(function(err) {
              console.log('Fetch Error', err);
          });
    }
    

    阅读有关 fetch 的更多信息:Introduction to fetch()

    【讨论】:

    • 谢谢,这对我帮助很大:)
    • 还需要注意的是,由于W3 Standards,只有Cache-ControlContent-LanguageContent-TypeExpiresLast-ModifiedPragma 在外部发出请求时可以访问域。
    【解决方案2】:

    您可以从response.headers获取标头

    fetch(URL_REGISTER, {
      method: 'POST',
      body: formData
    })
      .then((response) => {
        console.log(response.headers); //Returns Headers{} object
    }
    

    【讨论】:

    • 我试图像这样编辑 .then((response) => {console.log(response.headers); response.json()}) ,但是当我运行它时,它会显示错误,因为它没有读取 response.json() 。有什么想法吗?
    • @sptra, .json() 返回一个 Promise,因此要以 JSON 格式获取响应,您需要处理该 Promise:.then(function (response) { console.log(response.headers); return response.json(); }).then(function (json) { console.log(json); }).catch...
    【解决方案3】:

    您应该像
    return response.json();

    一样返回 response.json()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      • 2017-02-26
      • 1970-01-01
      相关资源
      最近更新 更多