0

i want to send some json data from my client page to server page of node.js, here i have my server page :

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

app.use(bodyParser.json());

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

app.listen(8081);
console.log('listening on 8081');

client page:

var name ='someName';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState== 4 && this.status == 200){
  console.log(this.responseText);
	}
};
xhttp.setRequestHeader({'Content-Type': 'application/json'});
xhttp.open('POST', 'http://localhost:8081', true);
xhttp.send(JSON.stringify({'name' : name}));

I got the result as a null json {}.

NOTE: I don't want to about submission of a form , i just want to send JSON data from html file to node.js file.

1
  • i got the response on html page as received request, but get a null json on server page. Commented Jul 5, 2017 at 15:07

1 Answer 1

1

The correct signature for a call to XMLHTTPRequest#setRequestHeader is setRequestHeader(header, value);

Change

xhttp.setRequestHeader({'Content-Type': 'application/json'});

to

xhttp.setRequestHeader('Content-Type', 'application/json');

Docs: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader

Sign up to request clarification or add additional context in comments.

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.