如何修复 async/await 函数中的“response.json 不是函数”

Cam*_*Cam 5 javascript reactjs

试图将我的回复转换为 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}`)
        }

    }
Run Code Online (Sandbox Code Playgroud)

我希望看到 json 响应,但收到错误消息。编辑:在 response.json() 前面添加了 await;却无处可去。

小智 8

您缺少对 fetch 的调用(或用于从 api 获取数据的任何其他方法)。现在看起来你误认为await是一个函数。

const response = await(`http:api.bart.gov...

(你也错过了后面的两个斜杠,http但这还不是问题。)

尝试这个:

const response = await fetch(`http://api.bart.gov...


Fer*_*big 7

您正在使用await作为函数

await是一个仅等待承诺而不执行的系统

const 响应 = wait('http:...');

你应该做

const response = await fetch('http:...');
Run Code Online (Sandbox Code Playgroud)