当我试图使用来自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>
我试图在"text“元素中使用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');
});
当fetch请求myaction表示返回名称查询时,由于它打印的是“对象响应”而不是名称表单值,所以在获取时不能使用它,我能做什么?
发布于 2021-12-31 09:39:25
全局fetch
函数返回解析为Response
对象的承诺。该对象包含有关响应的所有信息,如头、状态、正文等。要获得响应的主体,首先需要对响应进行解码。
在您的例子中,您需要将主体读入字符串,所以我们将使用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";
});
发布于 2021-12-31 09:44:50
从fetch返回的“响应”是一个不仅仅是响应中的数据的对象。它是一个Response
对象,这意味着它包含状态代码(比如200)以及数据。通常,您可以使用response.json()
(如果是JSON格式)或response.text()
(如果是文本)从响应中获取数据。这些函数是异步的,因此也返回了一个承诺。所以您的代码可以如下所示:
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://stackoverflow.com/questions/70544335
复制相似问题