Reputation: 2636
I'm trying to write a simple Express applicaiton that recieves JSON in a Post request. Here is what I have so far on the server:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/acceptContacts', function(req, res) {
'use strict';
console.log(req.body);
console.log(req.body.hello);
res.send(200);
});
app.listen(8080);
And here is what I have on the client in the browser:
var req = new XMLHttpRequest();
req.open('POST', 'http://localhost:8080/acceptContacts?Content-Type=application/json');
var obj = {hello:'world'};
req.send(JSON.stringify(obj))
However, I recieve the following output on the server's console:
{}
undefined
Can anyone suggest the cause?
Upvotes: 18
Views: 22526
Reputation: 15797
It will work if you use setRequestHeader
:
var req = new XMLHttpRequest();
req.open('POST', 'http://localhost:8080/acceptContacts');
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
var obj = {hello:'world'};
req.send(JSON.stringify(obj));
Upvotes: 20