Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The node express's bodyParser can't get the parameter in the GET request

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?

like image 215
hh54188 Avatar asked Dec 23 '12 14:12

hh54188


People also ask

What does bodyParser text () do?

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.

How do you access GET parameters after express?

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.

What is the alternative of bodyParser?

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?

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.


2 Answers

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

like image 188
Dominic Barnes Avatar answered Sep 22 '22 15:09

Dominic Barnes


You can access your data for get request in server-side by using req.query.key and req.query.value.

like image 33
sam100rav Avatar answered Sep 24 '22 15:09

sam100rav