[javascript] ReadableStream 객체에서 데이터를 검색 하시겠습니까?

ReadableStream객체 로부터 정보를 얻으려면 어떻게 해야합니까?

Fetch API를 사용 중이며 설명서에서 명확하지 않은 것으로 보입니다.

본문이로 반환되고 있으며이 ReadableStream스트림 내의 속성에 간단히 액세스하고 싶습니다. 브라우저 개발 도구의 응답 에서이 정보가 JavaScript 객체의 형태로 속성으로 구성되어있는 것으로 보입니다.

fetch('http://192.168.5.6:2000/api/car', obj)
    .then((res) => {
        if(res.status == 200) {
            console.log("Success :" + res.statusText);   //works just fine
        }
        else if(res.status == 400) {
            console.log(JSON.stringify(res.body.json());  //res.body is undefined.
        }

        return res.json();
    })



답변

의 데이터에 액세스하려면 ReadableStream변환 방법 중 하나를 호출해야합니다 ( 여기에서 사용 가능한 문서 ).

예로서:

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(function(response) {
    // The response is a Response instance.
    // You parse the data into a useable format using `.json()`
    return response.json();
  }).then(function(data) {
    // `data` is the parsed version of the JSON returned from the above endpoint.
    console.log(data);  // { "userId": 1, "id": 1, "title": "...", "body": "..." }
  });

편집 : 데이터 반환 유형이 JSON이 아니거나 JSON을 원하지 않는 경우text()

예로서:

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(function(response) {
    return response.text();
  }).then(function(data) {
    console.log(data); // this will be a string
  });

이것이 문제를 해결하는 데 도움이되기를 바랍니다.


답변

어떤 사람들은 async유용한 예를 찾을 수 있습니다 .

var response = await fetch("https://httpbin.org/ip");
var body = await response.json(); // .json() is asynchronous and therefore must be awaited

json()응답의 본문을 a ReadableStream에서 json 객체 로 변환 합니다.

await문은에 싸여해야 async하지만 당신은 실행할 수 있습니다, 기능 await(버전 62로) 크롬의 콘솔에서 직접 문을.


답변

res.json()약속을 돌려줍니다. 시도해보십시오 …

res.json().then(body => console.log(body));


답변

파티에 조금 늦었지만 ReadableStreamSharepoint Framework를 사용하여 Odata $ batch 요청에서 생성 된 유용한 정보를 얻는 데 문제가있었습니다 .

OP와 비슷한 문제가 있었지만 필자의 경우 해결책은과 다른 변환 방법을 사용하는 것이 었습니다 .json(). 제 경우 .text()에는 매력처럼 일했습니다. 그러나 텍스트 파일에서 유용한 JSON을 얻으려면 약간의 조정이 필요했습니다.


답변

그냥 텍스트로 응답을 원하는 경우에, JSON으로 변환 할 사용하지 https://developer.mozilla.org/en-US/docs/Web/API/Body/text를 하고 then그것은 실제를 얻을 수 약속의 결과 :

fetch('city-market.md')
  .then(function(response) {
    response.text().then((s) => console.log(s));
  });

또는

fetch('city-market.md')
  .then(function(response) {
    return response.text();
  })
  .then(function(myText) {
    console.log(myText);
  });


답변

나는 체인 연결을 싫어합니다. 두 번째는 상태에 액세스 할 수 없습니다. 앞서 언급 한 것처럼 ‘response.json ()’은 약속을 반환합니다. 그런 다음 ‘response.json ()’의 결과를 반환하는 것은 초와 비슷합니다. 응답 범위 내에 추가 보너스가 있습니다.

return fetch(url, params).then(response => {
    return response.json().then(body => {
        if (response.status === 200) {
            return body
        } else {
            throw body
        }
    })
})


답변

스트림을 한 번만 읽을 수 있으므로 반복해서 읽으려면 응답을 복제해야 할 수도 있습니다.

fetch('example.json')
  .then(res=>res.clone().json())
  .then( json => console.log(json))

fetch('url_that_returns_text')
  .then(res=>res.clone().text())
  .then( text => console.log(text))