快递post收不到JSON数据[关闭]

Express post not receive JSON data [close]

我遇到这个问题是因为我使用 XMLHttpRequest 通过 JavaScript 发送数据,但没有在 node.js express post 方法中接收数据。我不知道我做错了什么。

我的脚本 - 函数形式在 window 加载时执行

function form() {
  const btn = document.getElementById("save-data");
  let currentPage = window.location.href.split("/").at(-1);

  function sendData(data) {
    const XHR = new XMLHttpRequest();
    XHR.open("POST", window.location.href);
    XHR.setRequestHeader("Content-Type", "application/json");
    console.log(data); // I get right data
    XHR.send(data);
  }

  btn.addEventListener("click", () => {
    switch (currentPage) {
      case "settings":
        const prefix = document.getElementById("prefix").value;
        let buttonState = document.getElementById("module-state");

        if (buttonState.hasAttribute("enable")) {
          buttonState = "enable";
        } else {
          buttonState = "disable";
        }

        sendData({
          prefix: prefix,
          buttonState: buttonState,
          announcements: {
            giveawayChannelID: 123,
            updateChannelID: 123,
          },
        });
    }
  });
}

我的Node.js代码

router.post('/:id/settings', (req, res) => {
   console.log(req.body) // {}
})

请帮忙。

您需要通过 NPM 安装 body-parser 包,并在您的代码中引入它

尝试

npm i body-parser

然后在你的主节点脚本中,需要它

const bodyParser = require('body-parser');

之后,你应该将它设置为 express 的中间件

app.use(bodyParser.json()); //Handles JSON requests
app.use(bodyParser.urlencoded({ extended: false })); //Handles normal post requests

完成这些步骤后,您可以访问 req.body.value

等值