1

I am passing variable from AJAX to Node JS server but, when trying to extract the data from the request I keep getting [Object Object]. How would I get the data passed from AJAX to Node ?

AJAX:

$.ajax({
            type: "POST", 
            url: "/Watch", 
            data: {"name" : stockName},
            contentType: "json", 
            success: function(d) {
                //Stuff happening
            }, 
            error: function(d) {
                console.log("Error");
            }
        });

Node JS Server:

app.post('/Watch', function(req, res) {     

console.log("DATA from AJAX = " + req.body);//Returns [Object Object]
console.log("DATA from AJAX = " + req.body.data);//Returns 'undefined'
console.log("DATA from AJAX = " + req.data);//Returns 'undefined'
console.log("DATA from AJAX = " + req.name);//Returns 'undefined'
console.log("DATA from AJAX = " + req.body.data);//Returns 'undefined'  

res.send("");
});

In the Node JS the console.log shows some of the different thing I tried to get the data from the request.

7
  • Are you sure you have app.use(bodyParser.json()) or something similar added before this route handler? Commented Oct 28, 2016 at 17:06
  • Yes I do, at the top of the file Commented Oct 28, 2016 at 17:07
  • Then you may need to explicitly JSON.stringify() your data and use a full contentType like 'application/json'. Commented Oct 28, 2016 at 17:08
  • 1
    ok, I will apply your suggestions but, what is the correct code to extract the data from the request ? Commented Oct 28, 2016 at 17:15
  • What you have is generally fine, but it would be req.body.name for example. Commented Oct 28, 2016 at 17:23

2 Answers 2

2

With the help of @mscdex the solution was

AJAX :

alert(JSON.stringify({"name" : stockName}));
        $.ajax({
            type: "POST", 
            url: "/Watch", 
            data: JSON.stringify({"name" : stockName}), 
            contentType: "application/json", 
            success: function(d) {
                //Stuff                 
            }, 
            error: function(d) {
                console.log("Error");
            }
        }); 

Node JS:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var port = process.env.PORT || 5000;

app.use(bodyParser.json());   

app.post('/Watch', function(req, res) {
    console.log("In Watchlist POST");

    console.log("DATA from AJAX = " + req.body.name);//This was the solution    

    res.send("Finished Watchlist post");
});

app.use(express.static('public'));

app.listen(port, function () {
    console.log('App listening on port ' + port);
});
Sign up to request clarification or add additional context in comments.

Comments

1

Use res.format to format and send to the content-type requested,

res.format({
  'text/plain': function(){ 
   res.send( 'some json string inside quotes' );
},
 'text/html': function(){
  res.send('sending html response');
               },
'application/json': function(){
  res.json({ 
     success: true,
     messge: 'what you requested',
  });
},
'default': function() {
  res.status(406).send('Invalid format requested!');
}
});

you can populate the data anyway you need. on javascript, just evaluate the string on get/post eval('('+ msg + ')');

$.ajax { 
...
success: function (msg, statusText) {
     console.log("Response: " + msg);
     msg = eval('('+ msg + ')');
     $('.result').html(msg.status);
     console.log(msg);

},
....
});

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.