微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决无法使用 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 举报,一经查实,本站将立刻删除。