2016-07-29 2 views
1

내가 Fetch API으로보기 시작하고 내 샌드 박스에 나는 그것이 내가에서 가져 오는 경우XML 응답을 원 상태 코드 0 반환 API를 가져 오기

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

를 통해 JSON 객체의 배열을 반환 https://api.github.com/users/octocat/gists에서 가져 얻을 수 있습니다 XML을 리턴하는 private API, 어떤 종류의 변경이 필요합니까? 나는

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

을 추가하지만 정의되지 않은 상태 코드 0과 콘솔 인쇄 데이터를 점점 계속. 가져 오기가 응답이 JSON이라고 가정하기 때문에입니까?

또한 Chrome DevTools의 네트워크 탭에서 예상 한 XML 응답을 볼 수 있습니다.

<?xml version="1.0"?> 
<psgxml> 
    <years> 
    <year>1974</year> 
    <year>1952</year> 
    <year>1928</year> 
    </years> 
</psgxml> 
내가 CONSOLE.LOG를 통해

감사이 XML 응답을 인쇄하고 싶은

!

답변

0
당신은 객체로 XML을 구문 분석하는 데 실패 response.json()를 호출

, 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) 
    }) 
} 
+0

고마워요! 나는 틀린 것을 깨달았고, 나는 또 다른 것이 필요하다. 첫째로, 그 다음 약속입니다. – Nikkawat

0

해결에 그 변경! : D

나는 "아니 '액세스 제어 - 허용 - 원산지'헤더를로드 할 수 없습니다 API를 가져 오기"오류를 수신 한 이후 서버에서 일부 설정을 활성화해야한다고
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 밖으로 ...

2. 첫 번째 것은 약속을 처리하고 두 번째 것은 응답을 텍스트로 변환하는 데 사용할 수 있습니다.

관련 문제