我在嘗試使用來自 express 的回應時收到物件回應,這是我正在使用的 HTML 和客戶端 js
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<form method="post">
<input id="names" name="names" type="text" />
</form>
<button id="send">send</button>
<p id="text"></p>
<script>
document.getElementById("send").addEventListener("click", () => {
let datos = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
names: document.getElementById("names").value,
}),
};
fetch("/myaction", datos)
.then(function (response) {
document.getElementById("text").innerHTML = response;
})
.catch(() => {
document.getElementById("text").innerHTML = "Error";
});
});
</script>
</body>
</html>
我試圖在“文本”元素中使用 server.js 的回應,服務器是
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(express.json())
//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(express.bodyParser());
app.get('/', function(req, res) {
res.sendFile(__dirname "/index.html");
});
app.post('/myaction', function(req, res) {
res.send(req.body.names);
});
app.listen(8088, function() {
console.log('Server running');
});
當獲取請求 myaction express 回傳名稱查詢但我不能在獲取時使用它然后因為它列印“[物件回應]”而不是名稱表單值,我該怎么辦?
uj5u.com熱心網友回復:
全域fetch函式回傳一個決議為Response物件的 Promise 。該物件包含有關回應的所有資訊,如標頭、狀態、正文等。要獲得回應的正文,您需要先對回應進行解碼。
在您的情況下,您需要將正文作為字串讀取,因此我們將使用response.text(). 這是Response物件上的方法。它還回傳一個決議為字串的承諾。
fetch("/myaction", datos)
.then(function (response) {
return response.text();
})
.then(function (text) {
document.getElementById("text").textContent = text;
})
.catch(() => {
document.getElementById("text").textContent = "Error";
});
uj5u.com熱心網友回復:
從 fetch 回傳的“回應”是一個物件,它不僅僅包含回應中的資料。它是一個Response物件,這意味著它包含狀態代碼(如 200)以及資料。通常,您可以使用response.json()JSON 格式或response.text()文本格式從回應中獲取資料。這些函式是異步的,因此也回傳一個 Promise。所以你的代碼可以是這樣的:
fetch("/myaction", datos)
.then(function (response) {
return response.text(); // a Promise that will resolve to the data
})
.then(function (text) {
document.getElementById("text").innerHTML = text;
})
.catch(() => {
document.getElementById("text").innerHTML = "Error";
});
每當您看到一個看起來像[object Object]它的字串時,就意味著您看到的 Javascript 物件沒有有意義的toString()函式,因此這是向您展示值的最佳方法。如果您不確定它是什么型別的物件,一個好的除錯技術是使用輸出它,console.log(obj)這樣您就可以看到它的樣子。這通常會為您提供有關您真正在使用什么的線索。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/399362.html
標籤:javascript 节点.js 表达
