문제

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?

도움이 되었습니까?

해결책

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));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top