Javascript 获取API返回状态代码0,需要XML响应
我开始查看我的沙盒,在沙盒中,我可以从中获取并通过Javascript 获取API返回状态代码0,需要XML响应,javascript,json,xml,fetch-api,Javascript,Json,Xml,Fetch Api,我开始查看我的沙盒,在沙盒中,我可以从中获取并通过 function getGithubGists() { fetch('https://api.github.com/users/octocat/gists') .then(function(response) { response.json().then(function(data) { console.log('data', data) }) }) .catch(functio
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,console打印未定义的数据。这是因为fetch假设响应是JSON吗
另外,在ChromeDevTools的网络选项卡中,我可以看到我期望的XML响应
<?xml version="1.0"?>
<psgxml>
<years>
<year>1974</year>
<year>1952</year>
<year>1928</year>
</years>
</psgxml>
1974
1952
1928
我想通过console.log打印这个XML响应
谢谢 如果调用的
response.json()
无法将XML解析为对象,请将其更改为response.text()
解决了!: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无法加载无“Access Control Allow Origin”头”
2.需要两个。因为第一个处理承诺,然后第二个可以用于将响应转换为文本。谢谢!我意识到出了什么问题,我需要另一个。然后才能得到数据。首先,然后是承诺。
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))
}