简体   繁体   中英

input value is undefined from form

I am trying to access form data using GET method but it is giving me undefined.

URL: GET /search?email=dsdsd%40gmail.com

In my view I am creating form as:

          // search.jade
         // register form
                form(method='GET' action='/search')
                    div.form-group
                    label(for='email') Email:
                    input#favoriteBook.form-control(type='email', placeholder='' name='email' required)
                    button.btn.btn-primary(type='submit') Search

And in my app.js:

                app.get('/search',function(req,res){ // Performing search
                console.log(req.body.email); // getting UNDEFINED 
                loadSchema.find({email: req.body.email},function(err,users){
                    res.render('list',{users: users});
                });
            });

The problem is that you are trying to access the body of the GET request, but the GET request does not have a body to access the body you would have to use a POST request, but since you are sending the value as a query string param, in your express code you can catch it this way:

app.get('/search',function(req,res){ // Performing search
            console.log(req.params.email); // no UNDEFINED 
            loadSchema.find({email: req.params.email},function(err,users){
                res.render('list',{users: users});
            });
        });

The query string params go under req.params.attributeName

You can access query string parameter from req.query object. So, you can get email property value at req.query.email . For more information about req.query, check http://expressjs.com/en/api.html#req.query . Please change to the following in your app.js

 app.get('/search',function(req,res){ // Performing search
   console.log(req.query.email); // prints email value
   loadSchema.find({email: req.query.email},function(err,users){
     res.render('list',{users: users});
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM