问题
i am trying to pass a variable from jQuery to nodejs, but i am not getting the right results, nodejs returns [object Object]. how can it return a string variable on nodejs side.
$('.test').click(function(){
var tsId = "Hello World";
alert(tsId);
console.log(tsId);
$.ajax({
'type': 'post',
'data':tsId,
'url': '/test/testing',
'success': function (data) {
alert(data);
}
})
});
router.post('/testing', function(req, res) {
var tsID = req.body;
console.log("stsID "+tsID );\\ outputs [object Object]
});
回答1:
I recommend you to use this way:
You should pass an object in ajax data
, which contains your Hello World
string.
$.ajax({
type: 'post',
data:{str:tsId},
url: '/test/testing',
success: function (data) {
alert(data);
}
});
In node.js file use this:
router.post('/testing', function(req, res) {
var tsID = req.body;
console.log("stsID "+tsID.str );
});
回答2:
Try console logging tsID.data or tsID.tsId. What do you get? What do you get if you throw a debugger before your console log and write "tsID" in the console?
来源:https://stackoverflow.com/questions/41665948/passing-variable-from-jquery-ajax-to-nodejs