Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
154
rated 0 times [  157] [ 3]  / answers: 1 / hits: 44626  / 11 Years ago, sat, february 23, 2013, 12:00:00

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?


More From » jquery

 Answers
19

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());

[#80044] Thursday, February 21, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
frederickmohamedw

Total Points: 21
Total Questions: 123
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
frederickmohamedw questions
Wed, Sep 23, 20, 00:00, 4 Years ago
Sat, Jul 18, 20, 00:00, 4 Years ago
Sun, Apr 26, 20, 00:00, 4 Years ago
Sat, Jan 11, 20, 00:00, 4 Years ago
Fri, Dec 27, 19, 00:00, 4 Years ago
;