Nodejs从请求中获取[object Object]

时间:2016-10-28 17:03:45

标签: javascript ajax node.js

我将变量从AJAX传递到Node JS服务器但是,当我尝试从请求中提取数据时,我不断获得[Object Object]。如何将数据从AJAX传递到节点?

AJAX:

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

节点JS服务器:

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

在Node JS中,console.log显示了我尝试从请求中获取数据的一些不同内容。

2 个答案:

答案 0 :(得分:2)

在@mscdex的帮助下,解决方案是

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");
            }
        }); 

节点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);
});

答案 1 :(得分:1)

使用res.format格式化并发送到所请求的内容类型

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!');
}
});

您可以根据需要填充数据。在javascript上,只需评估get / post eval('('+ msg + ')');

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

},
....
});