Home > front end >  Why is the XMLHttpRequest request body returning null?
Why is the XMLHttpRequest request body returning null?

Time:04-20

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.

This is my client side code :

const user = {
    'Key' : 'user',
    'Name' : 'user',
    'Email' : '[email protected]',
    '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!

CodePudding user response:

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

CodePudding user response:

You will need a parser for the data/body you are sending. By default express does not parse the body part of the request.

You can add these two line in your express server to fix this.

app.use(express.json())
app.use(express.urlencoded({ extended: true}));
  • Related