grabbag grabbag - 5 months ago 19
Ajax Question

how to read ajax data in my nodejs express server

My webpage is able to get ajax data with the following code

$.ajax({
type: 'POST',
url: "/get_cache_transactions",
async: true,
data:
JSON.stringify({
a: 11,
b: 22,
c: 33
}),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) { process_cache_changes(data) },
error: function (xhr, ajaxOptions, thrownError) { }
})


but on the node express server can't read the parameter a, b, or c from the web page.

The nodejs express code is as follows

var express = require('express');

var app = express();

var handlebars = require('express-handlebars').create({ defaultLayout: 'main' });

app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');

app.use(require('body-parser').urlencoded({ extended: true }));

app.post('/get_cache_transactions', function (req, res) {
console.log("************************************************************************************************")

>>> how to I get value of a, b, c ?????


res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(pic_cache.cache, null, 2));
});


I tried printing out all of the attributes of req and nothing appears to contain a,b,or c. I tried to look at req.body and again nothing.

for (i in req.body){console.log(i)}


Also, my dependencies for this project are

"dependencies": {
"body-parser": "^1.15.1",
"cookie-parser": "^1.4.3",
"express": "^4.13.4",
"express-handlebars": "^2.0.1",
"express-session": "^1.13.0",
"formidable": "^1.0.17",
"fs": "0.0.2",
"parseurl": "^1.3.1"
},


in the chrome debugger (f12), i select network and see the following for the Post

General
Request URL:http://localhost:1662/get_cache_transactions
Request Method:POST
Status Code:200 OK
Remote Address:[::1]:1662
Response Headers
view source

Response Headers
Connection:keep-alive
Content-Length:631
Content-Type:application/json; charset=utf-8
Date:Sun, 26 Jun 2016 20:31:40 GMT
ETag:W/"277-PiWC2Y6iMvjEI1tGjkMrcw"
Request Headers
view source

Request Headers
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:22
Content-Type:application/json; charset=UTF-8
Cookie:connect.sid=s%3AOgJ3NCHzZpte0fSsxdLRDHK6Dggql1nC.entV9uoy%2BAHG5C3rNmt%2BrzdbZ9RDwDr%2B2FAqdx5%2BZKk
Host:localhost:1662
Origin:http://localhost:1662
Referer:http://localhost:1662/
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
X-Requested-With:XMLHttpRequest

Request Payload
view source
{a: 11, b: 22, c: 33}
a
:
11
b
:
22
c
:
33


So we know the a,b,c are being sent.

Answer

You are sending the data in JSON format. Try below code snippet for using the body-parser middleware & accessing the required values

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.post('/get_cache_transactions', function (req, res) {
   var a = req.body.a;
   var b = req.body.b;
   var c = req.body.c;

   //Rest of the code
})