简体   繁体   中英

Ajax vanilla Js sent post request is showing a blank body

I'm trying to print the data which has been received at the server side but it always shows a blank body output printing req={}

I've been trying for days and I can't find the answer, any help would be greatly appreciated!!!

the server side code:

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={}
});

The client side code:

<!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>

You need to have your express server use the JSON parser middleware. Add the following line to your server file.

app.use(express.json())

An explanation of the middleware is available at this link: http://expressjs.com/en/api.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM