Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从ReadableStream对象检索数据?_Javascript_Node.js_Reactjs_Fetch - Fatal编程技术网

Javascript 从ReadableStream对象检索数据?

Javascript 从ReadableStream对象检索数据?,javascript,node.js,reactjs,fetch,Javascript,Node.js,Reactjs,Fetch,如何从ReadableStream对象获取信息 我正在使用Fetch API,但从文档中看不清楚这一点 正文将作为ReadableStream返回,我只想访问此流中的一个属性。在浏览器开发工具中的响应下,我似乎将这些信息以JavaScript对象的形式组织到属性中 fetch('http://192.168.5.6:2000/api/car', obj) .then((res) => { if(res.status == 200) { con

如何从
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
  });
希望这有助于澄清问题。

res.json()
返回一个承诺。试试看

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

有些人可能会发现
async
示例很有用:

var response = await fetch("https://httpbin.org/ip");
var body = await response.json(); // .json() is asynchronous and therefore must be awaited
json()
将响应主体从
ReadableStream
转换为json对象


await
语句必须包装在
async
函数中,但是您可以直接在Chrome控制台中运行
await
语句(从版本62开始).

参加聚会有点晚,但在使用Sharepoint框架从Odata$batch请求生成的
ReadableStream
中获取有用信息时遇到了一些问题


与OP有类似的问题,但我的解决方案是使用不同于
.json()
的转换方法。在我的例子中,
.text()
就像一个符咒。但是,为了从文本文件中获取一些有用的JSON,需要进行一些修改。

如果您只想将响应作为文本,而不想将其转换为JSON,请使用,然后使用
然后
它以获得承诺的实际结果:

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


我不喜欢铁链。第二个则没有访问状态的权限。如前所述,“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))


我从他那里得到了答案。这对我有帮助。我认为这是因为API返回纯文本。

@Francescopezella感谢您的回复。我已经尝试了
response.Body.json()
,但是我得到了italic类型错误:无法读取未定义italic的属性“json”。这是因为bodyUsed属性也设置为false吗?但是,我可以在浏览器开发人员工具的“响应”选项卡下查看此正文。我想检索一条错误消息。那么您的问题完全与错误400条件有关?如果将处理程序更改为
console.log(res.json())?您是否看到了所需的数据?@noob如果
res.status==200
,您是否试图将响应作为流读取?是因为我还是文档完全错误?不过,我用这个答案的解决方案解决了这个问题。谢谢你的回复。我已经试过了,但是仍然得到了同样的错误,res.body是未定义的。我可以用res.status在first-then()函数中检索状态。似乎只有主体是ReadableStream对象。它似乎确实锁定了一个属性,该属性设置为true?您在哪里尝试访问
res.body
(这不是我的示例的一部分)?您能否在原始问题中共享一些示例代码,以便更清楚地说明您的问题所在。我尝试从first.then()函数中返回的json响应访问res.body。为了更清楚,我在原始问题中添加了一个示例。谢谢很棒,使用react和request native,想知道ReadableStream到底要做什么,这就成功了++只是一个headup,看起来很简单,但是要确保你访问的后端确实提供了有效的JSON!绝对不是凭经验说的。我试过了,它打印出了承诺而不是正文。尝试链接
。然后
调用:
获取(…)。然后(res=>res.json())。然后(data=>console.log(data))
谢谢!这对我有用。我正在用一个简单的
返回$data从我的Laravel服务器发送一个照亮的http响应。我终于能够通过
fetch(…)在浏览器中读取此响应。然后(response=>response.text())。然后(data=>console.log(data))链接
然后
帮助您检索最终解析的值(正文
)。嵌套它们会阻止您在没有回调或某种排序机制的情况下获取
body
值。想象一下:
let body=wait fetch(…)。然后(res=>res.json())。然后(data=>data)
。这不会以嵌套方式工作。要检查
响应。状态
,您始终可以
在第一个
中抛出一个异常,然后在整个承诺链中添加一个
捕获
。同意。在企业环境中优先考虑。:)有时候,你真正的答案是#2哈哈,他们为什么会使.json()异步,这是有道理的,但这并不是很明显。你可以详细说明不仅仅是一个链接吗?打开这个链接,你会看到我在解决方案中使用的代码,这对我的情况有帮助。在这段代码的末尾,我放置了回调函数而不是console.log。我不知道我能告诉你更多关于这件事的信息。是的,对于CityMarket.md
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))