Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON post requests in Node.js with Express 4

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?

like image 283
Jacob Horbulyk Avatar asked Apr 29 '14 12:04

Jacob Horbulyk


People also ask

Does Express automatically parse JSON?

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.

How do you post a request in node JS?

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.


1 Answers

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));
like image 124
MikeSmithDev Avatar answered Sep 20 '22 21:09

MikeSmithDev