下午好,我嘗試制作一個迷你應用程式,當您單擊按鈕時,會向后端進行提取并回傳一些資訊。
但我的問題是呼叫順利,因為它回傳 200 作為狀態,但資訊沒有到達。
這是客戶端代碼:
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>prueba</title>
</head>
<body>
<button type="submit" id="upload">received information</button>
<script>
const submitButton = document.getElementById("upload");
submitButton.addEventListener("click", (event) => {
event.preventDefault();
fetch("http://localhost:8000/", {
method: "GET",
}).then((res) => {
console.log("Request complete! response:", res);
});
});
</script>
</body>
</html>
這是服務器代碼:
import http from "node:http";
http.createServer((req, res) => {
const headers = {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
};
if (req.url === "/" && req.method === "GET") {
res.writeHead(200, headers);
res.write(JSON.stringify({ message: "Hello" }));
res.end();
return;
}
}).listen(8000, () => {
console.log("The server is active on the port 8000");});
這是服務器回應我的資料:
服務器回應我的資料的影像
uj5u.com熱心網友回復:
陳述句決議的是res回應fetch物件,而不是回應的文本。要獲取文本,請使用text()回應物件的函式:
fetch("http://localhost:8000/", {method: "GET"})
.then(res => res.text())
.then(text => {
console.log("Request complete! response:", text);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/529636.html
