Question

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?

Was it helpful?

Solution

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));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top