13

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?

1
  • I have the same problem - try use param('postVariableName') Commented Jan 8, 2014 at 23:58

2 Answers 2

9

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());
Sign up to request clarification or add additional context in comments.

3 Comments

Ahh, I knew I was missing something important! However, when I include this I started getting a 'Bad Request: Bad Request' response. Is this related in any way? Do I have to install this via npm?
@streetlight: I don't think you have to install anything, but I don't know what might be causing that error.
Ahh okay, thanks though for your help! There's almost nothing to this app so I have no idea what's going on with this bad request!
8

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.