首页 > 解决方案 > http.send 在后端返回 [object object] (Node + Express)

问题描述

我的 http.send 在 node.js 后端返回 [object object]。

    <script>
      const newExerciseForm = document.getElementById("newExercise");
      newExerciseForm.addEventListener("submit", function (e) {
        e.preventDefault();
        const http = new XMLHttpRequest();
        const userId = document.getElementById("uid").value;
        const description = document.getElementById("desc").value;
        const duration = document.getElementById("dur").value;
        const date = document.getElementById("dat").value;
        const params = userId + "," + description + "," + duration + "," + date;
        http.open(
          "POST",
          "http://localhost:5000/exercisetracker-f0756/europe-west1/exerciseTracker/api/exercise/add",
          true
        );

        //Send the proper header information along with the request
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        http.onreadystatechange = function () {
          //Call a function when the state changes.
          if (http.readyState == 4 && http.status == 200) {
            document.getElementById("exerciseTracker").innerHTML =
              http.responseText;
          }
        };
        http.send(params);
      });
    </script>

后端:

app.post('/api/exercise/add', (req, res) => {
  console.log(req.body)
  res.send('hitted');
})

有人可以帮我解决这个问题吗?由于应用程序的结构,我选择了标准的 xmlhttprequest 方法。

标签: javascriptnode.jsexpressobjectxmlhttprequest

解决方案


特里莫尔斯评论:使用“text/plain”可以立即与问题中的设置一起使用。

 //Send the proper header information along with the request
        http.setRequestHeader("Content-type", "text/plain");

谢谢!


推荐阅读