2

I'm running a server in nodejs with express to serve an html form within the file index.html to a client like this:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser());
app.get('/', function(req, res){res.sendfile('index.html');});
app.post('/', function(req, res){
  res.json(req.body);
});

app.listen(8080);

req.body gives me the form input. Now I need to send back req.body to the client, and to do this I'm using ajax on the client side (inside index.html) like this:

var data;
$('#submit').click(function()
{
    console.log('Button Clicked');
    $.ajax({
        url: '/',
        type:'POST',
        data: data,
        dataType: 'json',
        }).done(function(data) {

            console.log(data);
        });      
})

However when I click the button submit I get Object {} in the browser console and not the form input. What am I missing here?

7
  • I don't think you're using the body parser correctly. github.com/expressjs/body-parser Commented May 20, 2015 at 21:03
  • You are sending a JSON string and your server is converting to a JSON Object, which you are then returning - but not as a string. Try res.json(JSON.stringify(req.body)); Commented May 20, 2015 at 21:06
  • the result of that was {} Commented May 20, 2015 at 21:09
  • 1
    @Vic res.json expects an object, not json. :) Commented May 20, 2015 at 21:26
  • I think you should use bodyparser something like app.use(bodyParser.json({type: 'application/json'})); Commented May 20, 2015 at 21:41

1 Answer 1

1

There are two issues in your code:

First, as the comments mention, bodyParser() is deprecated, you should be using the specific bodyParser middlewares (json, text, urlencoded, raw). So in your case:

app.use(bodyParser.json())

Second, your client side call to jQuery.ajax should stringify your data. Like this:

$('#submit').click(function()
{
    console.log('Button Clicked');
    $.ajax({
        url: '/',
        type:'POST',
        data: JSON.stringify(data),
        dataType: 'json',
        }).done(function(data) {
            console.log(data);
        });      
})
Sign up to request clarification or add additional context in comments.

2 Comments

also didn't work. Do you know where can I find any clear examples of this?
It works for me... Are you assigning var data a value or is it undefined like in your code sample? What do you mean by 'it doesn't work'?

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.