Javascript 处理来自API cat facts的可读流响应
我做了一个非常简单的任务,从API获取信息,但后来我得到了ReadableStream的响应,事情开始像往常一样变暗。我正在尝试使用cat事实API 网址: 并使用VueJS渲染结果。我在网上找到的,但是这个代码只是返回一些随机数 代码如下:Javascript 处理来自API cat facts的可读流响应,javascript,vue.js,Javascript,Vue.js,我做了一个非常简单的任务,从API获取信息,但后来我得到了ReadableStream的响应,事情开始像往常一样变暗。我正在尝试使用cat事实API 网址: 并使用VueJS渲染结果。我在网上找到的,但是这个代码只是返回一些随机数 代码如下: created() { this.getFacts(); }, methods: { getFacts() { let vm = this; fetch('http://localhost:8080/facts')
created() {
this.getFacts();
},
methods: {
getFacts() {
let vm = this;
fetch('http://localhost:8080/facts')
.then(response => {
const reader = response.body.getReader();
return new ReadableStream({
start(controller) {
return pump();
function pump() {
return reader.read().then(({ done, value }) => {
// When no more data needs to be consumed, close the stream
if (done) {
controller.close();
return;
}
// Enqueue the next data chunk into our target stream
vm.facts = value;
controller.enqueue(value);
return pump();
});
}
}
})
})
.catch(err => console.error(err));
},
}
我正在使用vue.config.js管理cors错误:
module.exports = {
devServers = {
proxy: 'https://cat-fact.herokuapp.com/'
}
}
我向邮递员提出了这个要求,工作得很好。如果你这样做会发生什么:
async getFacts(){
让vm=这个;
const response=等待获取('http://localhost:8080/facts');
const myJson=wait response.json();
log(JSON.stringify(myJson));
}
如果你需要使用泵
的话,就不要喝了
编辑
无async/await
fetch('http://localhost:8080/facts')
.then(response=>response.json())
.then(data=>console.log(data));
如果您这样做会发生什么:
async getFacts(){
让vm=这个;
const response=等待获取('http://localhost:8080/facts');
const myJson=wait response.json();
log(JSON.stringify(myJson));
}
如果你需要使用泵
的话,就不要喝了
编辑
无async/await
fetch('http://localhost:8080/facts')
.then(response=>response.json())
.then(data=>console.log(data));
我尝试使用ajax和用php制作的代理,使用guzzle与API通信,效果很好!只是一句简单的话。但我对fetch方法的工作原理感到非常困惑 我尝试使用ajax和一个用php制作的代理,使用guzzle与API通信,效果很好!只是一句简单的话。但我对fetch方法的工作原理感到非常困惑 >返回“RealEnristRebug:ReGeaRealRunTime:未定义”。我已经尝试过,邮递员返回一个看起来像您建议的那样可管理的对象,但是在这中间可能有一些东西…哦,您可能会因为您的Env没有正确地设置<代码> AycNc/As/<代码>而得到这个错误。使用.then()
尝试同样的方法。您能解释一下吗?刷新页面并尝试下面的代码EDIT
@francogiovathat返回“ReferenceError:retinatorruntime is not defined”我已经尝试过了,POSTMAN返回了一个似乎可以按照您建议的方式管理的对象,但是在这中间可能会有一些东西…哦,你可能会因为你的Env没有正确地设置代码。使用.then()
尝试同样的方法。您能解释一下吗?刷新页面并尝试下面的代码编辑
@francogiova