Reputation: 127
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?
Upvotes: 2
Views: 4043
Reputation: 142
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);
});
Upvotes: 0
Reputation: 21
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);
});
Upvotes: 0
Reputation: 12552
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())
Upvotes: 1