繁体   English   中英

GET 请求的响应体为空

[英]Response body of GET request is empty

我正在尝试向我的服务器发出一个简单的 GET 请求。 URL 是对的,它使用 python ZC1C425268E68385D1AB5074C17A94 给出 json。 但我无法在 javascript 中获得相同的数据。 这个 function 有问题。

        async function get_status(){
            socket.send("Status!");
            URL = http://127.0.0.1:8000/api/status/';
            response = await fetch(URL, {
                method: "GET",
                headers: {
                    "Accept": "application/json"
                }
            })
            socket.send(response.json());
            console.log(response.json());
            if (response.ok) {
                current = document.getElementById("status");
                current.value= response.json()["status"];
             }
        };

请尝试:

const response = await fetch(URL);
if (response.ok) {
    const json = await response.json();
    console.log(json);
    socket.send(json);
    current = document.getElementById("status");
    current.value= response.json()["status"];
} else {
    console.log('request failed', response);
}

解释

fetch(URL)返回Promise<Response>并且 Response 实现了Body接口,这意味着response.json()返回另一个 promise 你应该“等待”。

此外,只有当响应返回ok时,您才能获取response.json() ,这意味着该代码应该在包装内执行if (response.ok) {...

有关更多信息,请参阅: https://www.npmjs.com/package/node-fetch#fetchurl-options

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM