I ajax an GET request in client side:
$.ajax({
url: '/update',
type: 'get',
data: {
"key": key,
"value": value
},
success: function (data, err) {
}
})
then at the node side, I want get the parameter
var showParam = function (req, res) {
if (req.body) {
for (var key in req.body) {
console.log(key + ": " + req.body[key]);
}
res.send({status:'ok',message:'data received'});
} else {
console.log("nothing received");
res.send({status:'nok',message:'no Tweet received'});
}
}
app.get('/update', function(req, res){
showParam(req, res);
})
The shell show the body is empty and undefined.
But when I change the get to post (both at the client side and server side), everything is ok, I can get the parameter correctly.
What's problem with my code? Do I miss something?
If you are issuing a GET request, the URL parameters are not part of the body, and thus will not be parsed by the bodyParser middleware.
To access the query parameters, just reference req.query
In order to get params from bodyParser you must use POST not GET. Your ajax request and server calls must both use POST.
http://expressjs.com/api.html#req.body
app.post('/update', function(req, res){
showParam(req, res);
});
$.ajax({
url: '/update',
type: 'POST',
data: {
"key": key,
"value": value
},
success: function (data, err) {
}
});
To get the GET params, use the url module and use query = url.parse(req.url, true).query. query will contain an object with the values accessible via query.foo
You can access your data for get request in server-side by using req.query.key and req.query.value.