我的 POST 请求始终未定义,无法读取我的 JSON 对象

The POST request I have is always undefined, and can't read my JSON object

所以我正在使用 FS 和 Express 以及 BodyParser 构建一些博客软件。无论如何,当我发送 POST 请求时(使用 Fetch API)

当我输入正确的密码(作为 config.js 文件中的 .env 变量)时,它说密码不正确,并且猜测未定义。我已经尝试了很多,但没有任何效果。 (我的 undo() 函数删除符号和 returns 输出。)

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({ strict:false }));
app.post("/newpost", (req, res) => {
  if (req.body.password == config.PASSWORD) {
    fs.writeFile("/blog/" + undo(req.body.name) + ".md", req.body.context, (err) => {
      console.log("Probably made file. Error: " + err);
    });
  } else {
    console.error("Someone tried guessing and making a blog on your Blog. Stay safe. Their guess was " + req.body.password + ".");
  }
});

这里是添加新博客的功能:

var xv=prompt("Enter the password.");
var ob = {password: xv, name: document.getElementById("title").innerText, context: document.getElementById("context").innerHTML};
fetch("/newpost",{method:"POST", body:JSON.stringify(ob)});

当你转换成字符串时,这里-

var xv=prompt("Enter the password.");
var ob = {password: xv, name: document.getElementById("title").innerText, context: document.getElementById("context").innerHTML};
fetch("/newpost",{method:"POST", body:JSON.stringify(ob)});

你需要在这里转换回对象

app.use(bodyParser.json({ strict:false }));
app.post("/newpost", (req, res) => {
  req.body = JSON.parse(req.body);
  if (req.body.password == config.PASSWORD) {
    fs.writeFile("/blog/" + undo(req.body.name) + ".md", req.body.context, (err) => {
      console.log("Probably made file. Error: " + err);
    });
  } else {
    console.error("Someone tried guessing and making a blog on your Blog. Stay safe. Their guess was " + req.body.password + ".");
  }
});```