【问题标题】:Fetch API returning status code 0, want XML response获取 API 返回状态码 0,需要 XML 响应
【发布时间】:2016-07-29 23:09:59
【问题描述】:

我开始研究Fetch API,在我的沙盒中,我可以从https://api.github.com/users/octocat/gists 获取它,以通过

返回一组 JSON 对象
function getGithubGists() {
  fetch('https://api.github.com/users/octocat/gists')
    .then(function(response) {
      response.json().then(function(data) {
        console.log('data', data)
      })
    })
   .catch(function(error) {
      console.log('Error', error)
   })
}

如果我从返回 XML 的私有 API 获取,我需要进行哪些更改?我加了

  headers: {
    'Accept': 'text/xml'
  }

但我不断收到状态代码 0 并且控制台打印未定义的数据。这是因为 fetch 假设响应是 JSON 吗?

此外,在 Chrome DevTools 的网络选项卡中,我可以看到我期待的 XML 响应。

<?xml version="1.0"?>
<psgxml>
  <years>
    <year>1974</year>
    <year>1952</year>
    <year>1928</year>
  </years>
</psgxml>

我想通过 console.log 打印这个 XML 响应

谢谢!

【问题讨论】:

    标签: javascript json xml fetch-api


    【解决方案1】:

    解决了! :D

    function getXML() {
      fetch('https://privateapi.com/xml')     
      .then(response => response.text()) // the promise
        .then(data => console.log('Data', data)) // data
      .catch(error => console.log('Error', error))
    }
    

    1.我发现我必须在服务器中启用一些设置,因为我收到错误“Fetch API 无法加载 No 'Access-Control-Allow-Origin' 标头”...

    2.需要两个 .then 因为第一个处理承诺,然后第二个可用于将响应转换为文本。

    【讨论】:

      【解决方案2】:

      您正在调用 response.json(),它无法将 XML 解析为对象,请将其更改为 response.text()

      function getGithubGists() {
        fetch('https://privateapi.com/xml')
          .then(function(response) {
            response.text().then(function(data) {
              console.log('data', data)
            })
          })
         .catch(function(error) {
            console.log('Error', error)
         })
      }
      

      【讨论】:

      • 谢谢!我意识到出了什么问题,我需要另一个 .then 来获取数据。首先是承诺。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 2016-06-05
      • 2017-05-13
      • 1970-01-01
      • 2023-03-11
      • 2017-06-26
      • 1970-01-01
      相关资源
      最近更新 更多