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?
Express doesn't automatically parse the HTTP request body for you, but it does have an officially supported middleware package for parsing HTTP request bodies. As of v4. 16.0, Express comes with a built-in JSON request body parsing middleware that's good enough for most JavaScript apps.
Note: If you are going to make GET, POST request frequently in NodeJS, then use Postman , Simplify each step of building an API. In this syntax, the route is where you have to post your data that is fetched from the HTML. For fetching data you can use bodyparser package. Web Server: Create app.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With