无法使用post通过xmlhttprequest将json字符串从客户端发送到nodejs服务器

b5lpy0ml  于 2021-09-23  发布在  Java
关注(0)|答案(0)|浏览(179)

我在js和nodejs都是新手,为了达到这个目标,我已经被困了3天==>
通过以下方式将jsonstringified正文发送到服务器:

<!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('/', function(req, res) {
    var path = require('path');
    res.sendFile(path.resolve('index.html'));
  });

但是我从控制台(req.body)和控制台(req.params)得到的所有信息都是{}{},我仍然不知道json是被发送还是没有被接收,或者甚至没有被发送。我已经在服务器端尝试了大量关于cors和jsonparsing的建议,但这些都不起作用。我很乐意听取任何关于如何做到这一点的建议,甚至更好地了解我做错了什么背后的问题。谢谢。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题