IT

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

lottoking 2020. 9. 7. 08:25
반응형

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

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

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 ()'은 promise를 반환합니다. 'response.json ()'의 then 결과를 반환하는 것은 then과 비슷합니다. 응답 범위 내에 있다는 추가 보너스가 있습니다.

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

참고 URL : https://stackoverflow.com/questions/40385133/retrieve-data-from-a-Readablestream-object

반응형