Nikkawat
Nikkawat

Reputation: 79

Fetch API returning status code 0, want XML response

I started looking into Fetch API and in my sandbox I can get it to fetch from https://api.github.com/users/octocat/gists to return an array of JSON objects via

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

If I fetch from a private API that returns XML, what sort of changes would I need to make? I added

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

but I keep getting status code 0 and console prints data undefined. Is this because fetch assumes the response is JSON?

Also, in the Network tab of Chrome DevTools I can see the XML response I am expecting.

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

I would like to print this XML response via console.log

Thanks!

Upvotes: 1

Views: 3067

Answers (2)

Nikkawat
Nikkawat

Reputation: 79

Solved! :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.Figured out that I had to enable some settings in the server since I was receiving the error "Fetch API cannot load No 'Access-Control-Allow-Origin' header"...

2.Need two .then since first one handles the promise and then second one can be used to convert the response to text.

Upvotes: 1

Rob M.
Rob M.

Reputation: 36511

You are calling response.json() which is failing to parse the XML into an object, change that to 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)
   })
}

Upvotes: 0

Related Questions