当我点击按钮时,post请求正在发送,console.log在app.post中工作正常,但res.send()没有反映



当我点击带有类(.hw)的按钮时,post请求正在发送,console.log在app.post中工作正常,但res.send()没有反映在浏览器中。我也试图结束回应,但这没有任何区别。此外,这是我第一次使用堆栈溢出,而且我是绝对的初学者,所以请用简单的术语解释。

INDEX.js:

let obj = {
message: "hello world"
};
document.querySelector(".hw").addEventListener("click",()=>{
fetch("/",{
method: "POST",
headers: {
'Content-Type':'application/json',
},
body: JSON.stringify(obj),
}).then(data => {
console.log(data);
}).catch(err => console.log(err));
});

APP.js

const exp = require("express");
const app = exp();

app.get("/",(req,res)=>{
res.sendFile(__dirname+"/index.html");
req.on("close",() => res.end());
});
app.get("/index.js",(req,res)=>{
res.sendFile(__dirname+"/index.js");
});
app.post("/",(req,res) => {
req.on('data',data => {
console.log(JSON.parse(data).message);
res.send(JSON.parse(data).message);
});
});
app.listen(3000,()=>{
console.log("server started at 3000");
});

试试这个

fetch("/",{
method: "POST",
headers: {
'Content-Type':'application/json',
},
body: JSON.stringify(obj),
}).then(data => {
return data.json();
})
.then(resData=>{console.log(resData)})
.catch(err => console.log(err));

在后台

app.post("/",(req,res) => {
const data=req.body;
console.log(data);
res.send("request success") //res.json(data) for sending data back to UI
});

参见https://stackoverflow.com/a/72076993/16462950

作为自己解析JSON的另一种选择,您可以编写

app.post("/", express.json(), (req,res) => {
console.log(req.body.message);
res.send(req.body.message);
});