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?
bodyParser. text([options]) Returns middleware that parses all bodies as a string and only looks at requests where the Content-Type header matches the type option. This parser supports automatic inflation of gzip and deflate encodings.
Your query parameters can be retrieved from the query object on the request object sent to your route. It is in the form of an object in which you can directly access the query parameters you care about. In this case Express handles all of the URL parsing for you and exposes the retrieved parameters as this object.
Top Alternatives to body-parserTypeScript is a language for application scale JavaScript development. An AST-based pattern checker for JavaScript. TypeScript definitions for Node. js.
Is bodyParser deprecated 2021? “bodyparser is deprecated 2021” Code Answer's // If you are using Express 4.16+ you don't have to import body-parser anymore.
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
You can access your data for get request in server-side by using req.query.key
and req.query.value
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With