[英]How to fix 'response.json is not a function' in async/await function
試圖將我的回應變成json。 我不太確定我收到TypeError: response.json is not a function
錯誤。 有人能指出我正確的方向嗎? 提前致謝。
componentDidMount(){
this.timingFunction = setInterval(() => this.getAllStations(), 1000);
}
async getAllStations(){
try{
const response = await(`http:api.bart.gov/api/etd.aspx?cmd=etd&orig=${this.state.selectedStation}&key=${bartKey}&json=y`);
const data = await response.json();
console.log(`Here: ${data}`)
}catch(e){
console.log(`Error: ${e}`)
}
}
我希望看到json響應,但收到錯誤消息。 編輯:在response.json()前面添加了await; 卻無處可去
您丟失了對訪存的調用(或用於從api獲取數據的任何其他方法)。 現在看來,您似乎已經在await
功能。
const response = await(`http:api.bart.gov...
(您也錯過了http
后面的兩個斜杠,但這還不是問題。)
嘗試這個:
const response = await fetch(`http://api.bart.gov...
await(`http://api.bart.gov/api/etd.aspxcmd=etd&orig=${this.state.selectedStation}&key=${bartKey}&json=y`);
返回字符串,而不是響應。 我相信您想做的是:
await(fetch(`http://api.bart.gov/api/etd.aspxcmd=etd&orig=${this.state.selectedStation}&key=${bartKey}&json=y`));
您正在使用await作為函數
await
是僅等待諾言而不是做的系統
const response = await('http:...');
你應該做
const response = await fetch('http:...');
您應該在response.json();
之前添加await
response.json();
async getAllStations(){
try{
const response = await(`http:api.bart.gov/api/etd.aspx?cmd=etd&orig=${this.state.selectedStation}&key=${bartKey}&json=y`);
const data = await response.json();
console.log(`Here: ${data}`)
} catch(e) {
console.log(`Error: ${e}`)
}
}
嘗試使用諾言。
componentDidMount(){
this.timingFunction = setInterval(() => this.getAllStations().then(function(resolve){
console.log("Here:" + resolve)
},function(reject){
console.log("Error: " + reject)
}), 1000);
}
function getAllStations(){
return new Promise(function(resolve, reject){
try{
$.get("url",function(data){
resolve(data);
})
}
catch(e){
reject(e)
}
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.