Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading AJAX post variables in Node.JS (with Express)

I'm trying to get the values I'm sending for an ajax post in my node application. Using this post as a guide, I have this so far:

In Node:

 var express = require('express');
 var app = express();

 var db = require('./db');

 app.get('/sender', function(req, res) {
    res.sendfile('public/send.html');
 });

 app.post('/send_save', function(req, res) {
  console.log(req.body.id)
  console.log(req.body.title);
  console.log(req.body.content);
  res.contentType('json');
  res.send({ some: JSON.stringify({response:'json'}) });
});

app.listen(3000);

On on the AJAX side:

$('#submit').click(function() {
            alert('clicked')
            console.log($('#guid').val())
            console.log($('#page_title').val())
            console.log($('#page-content').val())
            $.ajax({
                url: "/send_save",
                type: "POST",
                dataType: "json",
                data: {
                    id: $('#guid').val(),
                    title: $('#page_title').val(),
                    content: $('#page-content').val()
                },
                contentType: "application/json",
                cache: false,
                timeout: 5000,
                complete: function() {
                  //called when complete
                  console.log('process complete');
                },

                success: function(data) {
                  console.log(data);
                  console.log('process sucess');
               },

                error: function() {
                  console.log('process error');
                },
              });
        })

This issue is that I can't req.body.id (and any other value like title or content), I'm getting this error in node:

 TypeError: Cannot read property 'id' of undefined

If I comment those calls out though, the ajax is successful. I am lost. Am I forgetting something?

like image 644
streetlight Avatar asked Feb 23 '13 15:02

streetlight


2 Answers

The req object you have there has no body property. Have a look at http://expressjs.com/api.html#req.body:

This property is an object containing the parsed request body. This feature is provided by the bodyParser() middleware, though other body parsing middleware may follow this convention as well. This property defaults to {} when bodyParser() is used.

So, you need to add the bodyParser middleware to your express webapp like this:

var app = express();
app.use(express.bodyParser());
like image 74
thejh Avatar answered Oct 28 '22 03:10

thejh


The issue was indeed resolved by including the bodyParser middleware as suggested by thejh.

Just make sure to visit the url provided in that answer as to visit Express updated specification: http://expressjs.com/api.html#req.body

The documentation provides this example (Express 4.x):

var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); 

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data

app.post('/', function (req, res) {
  console.log(req.body);
  res.json(req.body);
})

For this to work the body-parser module needs to be installed separately:

https://www.npmjs.com/package/body-parser

like image 35
Lex L. Avatar answered Oct 28 '22 04:10

Lex L.