I'm trying to do a simple GET request to my server. URL is right, it gives json using python function. But I can't get the same data in javascript. Something is wrong with this 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"];
}
};
Try instead:
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);
}
Explanation
fetch(URL)
returns Promise<Response>
and the Response implements the Body
interface which means that response.json()
returns another promise you should "await" on.
Further, you'll be able to fetch response.json()
only if the response returned ok
which means that this code should be executed inside the wrapping if (response.ok) {...
.
For more, see: https://www.npmjs.com/package/node-fetch#fetchurl-options
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.