반응형
Fetch Response 개체에서 텍스트 가져오기
사용하고 있다fetch
API 호출 및 모든 것이 작동하지만 이 경우 API가 오브젝트가 아닌 문자열을 반환하기 때문에 문제가 발생합니다.
일반적으로 API는 오브젝트를 반환하고 JSON 오브젝트를 해석하여 원하는 것을 얻을 수 있지만, 이 경우 응답 오브젝트에서 API에서 얻은 텍스트를 찾는 데 어려움을 겪고 있습니다.
본문 안에 있는 텍스트를 찾을 수 있을 줄 알았는데 찾을 수가 없네요.어디 봐요?
가져오기 JavaScript API를 사용하여 다음을 시도할 수 있습니다.
response.text().then(function (text) {
// do something with the text response
});
또, fetch > response > body interface 메서드에 관한 문서도 참조해 주세요.
ES6 구문:
fetch("URL")
.then(response => response.text())
.then((response) => {
console.log(response)
})
.catch(err => console.log(err))
이 작업은 다음 두 가지 방법으로 수행할 수 있습니다.
첫 번째 옵션은,
response.text()
그러나 2019년 12월 현재 글로벌 사용률은 36.71%에 불과하다는 점에 유의하십시오.async function fetchTest() { let response = await fetch('https://httpbin.org/encoding/utf8'); let responseText = await response.text(); document.getElementById('result').innerHTML = responseText; } (async() => { await fetchTest(); })();
<div id="result"></div>
두 번째 옵션은,
response.body
좀 더 많은 작업이 필요하지만 전체 사용량의 73.94%를 차지합니다.async function fetchTest() { let response = await fetch('https://httpbin.org/encoding/utf8'); let responseText = await getTextFromStream(response.body); document.getElementById('result').innerHTML = responseText; } async function getTextFromStream(readableStream) { let reader = readableStream.getReader(); let utf8Decoder = new TextDecoder(); let nextChunk; let resultStr = ''; while (!(nextChunk = await reader.read()).done) { let partialData = nextChunk.value; resultStr += utf8Decoder.decode(partialData); } return resultStr; } (async() => { await fetchTest(); })();
<div id="result"></div>
언급URL : https://stackoverflow.com/questions/41946457/getting-text-from-fetch-response-object
반응형
'programing' 카테고리의 다른 글
안심.request json에서 값을 추출할 수 있습니까? (0) | 2023.03.13 |
---|---|
Backbone.js - id vs idAttribute vs cid (0) | 2023.03.13 |
Spring WebFlux에서 요청 및 응답 본문을 기록하는 방법 (0) | 2023.03.13 |
Mongo 셸에서 Mongo 쿼리 출력을 파일로 인쇄하는 중 (0) | 2023.03.08 |
루트가 변경되면 Angular UI Bootstrap Modal을 자동으로 닫는 방법이 있나요? (0) | 2023.03.08 |