2

I have an html form that has several fields which I package in a JSON, and I need to send this to a server. I have the following code on the front end:

var data = {
//data here
};
var xhr = new XMLHttpRequest();
xhr.open("POST","localhost:8000/add",true);
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(data);

And then on the server, I have this code to receive it:

app.post('/add', function(req,res) {
  console.log(req.body.name);
  res.json(req.body.name);
});

It sends nothing; what do I need to do to get it to send the JSON?

3
  • 3
    Are you using the body parser? Commented Aug 3, 2018 at 18:48
  • Did you try to check req.body (console.log(req.body);) to see if you received any data or not ? Commented Aug 4, 2018 at 0:46
  • Possible duplicate of Express.js POST req.body empty Commented Aug 4, 2018 at 14:37

3 Answers 3

1

You need to use body-parser to get values in req.body

From npm documents

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())
Sign up to request clarification or add additional context in comments.

1 Comment

I included those, and still nothing gets sent.
0

You are not handling the response of post request,and also make sure you are using body parser at backend. So you front end code should be like this:

var data = {name:"xyz"};
var json = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.open("POST","localhost:8000/add",true);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
xhr.onload = function () {
    var data = JSON.parse(xhr.responseText);
   if (xhr.readyState == 4 && xhr.status == "201") {
    console.log(data);
  } else {
    console.log(data);
  }
}
xhr.send(json);

And your server side code should be coded like :

 var express = require('express')
   var bodyParser = require('body-parser')

   var app = express();
   // parse application/json
   app.use(bodyParser.json())

  // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: false }));

    app.post('/add', function(req,res) {
      console.log(req.body.name);
      res.status(201).json(req.body.name);
  });

1 Comment

this is now all blocked by CORS policy
0

I tested it with this code and it success with me:

Client code same as your code.

Server Code:

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

app.use(express.json());

app.post('/add', function(req,res) {
  console.log(req.body.name);
  res.json(req.body.name);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.