Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the XMLHttpRequest request body returning null?

I am trying to send a ‘POST’ XMLHttpRequest to my server, which uses express.
The server is able to recieve the request, but the request’s body is null.

On the server I am receiving it with :

app.post('/', function(req, res){
    res.send(req.statusCode);
    console.log(req.body);
})

I don’t think that there is a problem with it as many sources say that this is a good way to receive the request.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is my client side code :

const user = {
    'Key' : 'user',
    'Name' : 'user',
    'Email' : 'user@example.com',
    'Password' : 'password'
}

const jsonFileRequest = new XMLHttpRequest();
jsonFileRequest.open('POST', '/', true);
jsonFileRequest.setRequestHeader('Content-Type', 'application/json');

jsonFileRequest.onreadystatechange =  function(){
    console.log(`userStatus : ${jsonFileRequest.readyState},\nstatus: ${jsonFileRequest.status}`);
    if(jsonFileRequest.readyState == 4 && jsonFileRequest.status == 200)
    {
        console.log(`userStatus : âś…,\nstatus : âś…`);

    }
}
jsonFileRequest.send(JSON.stringify(user));

**This is my server side code : **

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

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/frontend/index.html');
    app.get('/index.html.js', (req, res) => {
        res.sendFile(__dirname + '/frontend/index.html.js');
    })
    app.get('/data.json', (req, res) => {
        res.sendFile(__dirname + '/data.json');
    })
})
app.post('/', function(req, res){
    res.send(req.statusCode);
    console.log(req.body);
})
app.listen(port);
console.log(`listening on http://localhost:${port}`);

Could you please help me? Thank you!

>Solution :

You should try using the express.json() middleware. When disabled (by default), req.body returns undefined.

You can check out the express documentation for more info:

req.body

Contains key-value pairs of data submitted in the request
body. By default, it is undefined, and is populated when you use
body-parsing middleware such as express.json() or
express.urlencoded().

See: https://expressjs.com/en/api.html

Using the following code snippet for your express server should work:

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Calling the express.json() method for parsing
app.use(express.json());

// Reading content-type
app.post('/', function (req, res) {
   console.log(req.body.name)
   res.end();
})

// Listening to the port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading