0

I'm trying to read data sent to node.js server.

Client side:

const sendToDB =(date)=> {
  var xhttp = new XMLHttpRequest();
  var d = JSON.stringify(date);
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log(d);
    }
  };
  xhttp.open("POST", "api/info", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send(d);
}

and the server:

var http = require('http');
var server = http.createServer(function(req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  req.on('data', function (chunk) {
    console.log(req.body.date);
  });
  res.end();
});
server.listen(3001);

how to receive data sent with xhttp.send(d) in node js server ?

2 Answers 2

1
var server = http.createServer(function(req, res) {
      if(req.method == "POST"){       
           var clientData = '';
           req.on('data', function (chunk) {
                clientData+=chunk;
           });
           req.on('end',function(){
                console.log(JSON.parse(clientData));
           })
      }
      res.end();
});
Sign up to request clarification or add additional context in comments.

Comments

0

you should use the header "Content-Type", "application/json" as you send some json data. make sure you send a such an object :

{
  date: {
    foo: bar
  }
}

as your server is expecting it in the body req.body.date

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.