【问题标题】:Ajax vanilla Js sent post request is showing a blank bodyAjax vanilla Js发送的帖子请求显示空白正文
【发布时间】:2021-04-28 21:13:31
【问题描述】:

我正在尝试打印在服务器端收到的数据,但它总是 显示空白正文输出打印req={}

我已经尝试了几天,但我找不到答案,任何帮助将不胜感激!!!

服务器端代码:

const express= require('express');
const app=express();

const data_itself = require('./data.js');

app.use(express.static('public'));
app.use(express.urlencoded({extended:true}));

app.listen(3100,()=>{
   console.log('sever listening at port 3100...')
});
app.set('view engine','ejs');
app.set('views','public');

app.get('/',(req,res)=>{
   res.redirect('/home');
});

app.post('/',(req,res)=>{
   var random_data='recived post request!'
   res.send(random_data);
   console.log('req=',req.body); //this outputs to req={}
});

客户端代码:

<!DOCTYPE html>

<head>
    <title>Sample Site</title>
</head>

<body>
    <button onclick="send_info()">Submit data</button>
    <div id="stat"></div>
</body>
<script>
    data=['xyz'];
        function send_info(){
          var xhr = new XMLHttpRequest();
          xhr.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
             document.getElementById("stat").innerHTML =
             this.responseText;
           }
          };
           xhr.open("POST",'/', true);
           xhr.setRequestHeader('Content-Type', 'application/json');
           xhr.send(JSON.stringify(data));
    
        }
</script>

</html>

【问题讨论】:

  • 您使用 urlencoded 正文解析器但发送 json 数据。选择一个或另一个(或使用两个正文解析器)
  • 您发送 JSON 以表达但从不发送 set up express to parse JSON

标签: javascript node.js ajax express


【解决方案1】:

您需要让您的快速服务器使用 JSON 解析器中间件。将以下行添加到您的服务器文件中。

app.use(express.json())

中间件的解释见此链接:http://expressjs.com/en/api.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多