无法使用 POST 通过 xmlhttprequest 从客户端向 Nodejs 服务器发送 Json 字符串

问题描述

我对 JS 和 Nodejs 还很陌生,我已经坚持了 3 天试图实现这一目标 ==>

通过以下方式将 jsonstringified body 发送到服务器:

<!DOCTYPE html>
<html>
<head>
  <title>
    JavaScript | Sending JSON data to server.
  </title>
</head>
<body style="text-align:center;" id="body">
  <h1 style="color:green;">
    Post Product
  </h1>
  <p>
  <form action='/' method="POST">
    <input type="text" id="name" placeholder="Product Name">
    <input type="text" id="price" placeholder="Price">
    <button id="btn">Send JSON</button>
    <p class="result" style="color:rgb(6,177,6)"></p>
  </form>
  <script>
    let button = document.querySelector("#btn");
    button.addEventListener("click",sendJSON,true);

    function sendJSON() {
      let name = document.querySelector("#name");
      let price = document.querySelector("#price");
      let url = "localhost:4000";
      let xhr = new XMLHttpRequest();

      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 201) {
          result.innerHTML = this.responseText;
        }
      };
      const json = [{name: name,price: price}];
      xhr.open('POST',url,true);
      xhr.setRequestHeader('content-type','application/json');
      alert(xhr)
      xhr.send(JSON.stringify(json));
    }
  </script>
  </p>
</body>
</html>

并通过以下方式获取服务器端的数据:

const express = require('express')
const routes = require('./routes/routes');
const cors = require('cors')
const server = express()

server.use(express.json())
server.use(cors())
server.set('view engine','ejs')
server.set("views",__dirname + "/views")

server.listen(4000,function() {
    console.log('http server on 4000 port')
});

server.post('/',function(req,res) {
    console.log(req);
    console.log(req.params)
    console.log(req.body)
});

server.get('/',res) {
    var path = require('path');
    res.sendFile(path.resolve('index.html'));
  });

但是我从控制台(req.body)和控制台(req.params)得到的都是{} {},我仍然不知道json是否正在发送和未收到,或者甚至没有发送。我已经在服务器端尝试了大量关于 cors 和 jsonparsing 的建议,但似乎没有任何效果。我很乐意就如何完成这项工作提出任何建议,甚至更好地了解我做错了什么背后的问题。非常感谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)