简体   繁体   中英

Issue with GET forms and Node.JS and Express

I've hot a very simple form in HTML, that sends GET information to my Node.JS server, with Express. This is the form:

    <form method="get" action="/search" autocomplete="off" class="navbar-search pull-left">
       <input name="search" type="text" id="search" data-provide="typeahead" placeholder="Search..." />
    </form>

And this is the server part:

app.get('/search', function (req, res){

   console.log(req.query["search"]);

   res.render('search.ejs')

});

When I write something to the input, and press enter, and the page keeps loading for a long while, and I receive a 340 error when I get in for example in http://localhost:8080/search?search=foo . I think I have a problem with the from, that doesn't send properly the values, because it doesn't work with POST request too. Any solution for this?

Thank's advance!

It is because you have to use the req.params.search instead of req.query which does not work.

app.get('/search', function (req, res){
   var search = req.query.search;

   console.log(search);

   res.render('search.ejs')

});

Here you can read more about it: http://expressjs.com/api.html#req.param

下次找出一个erorr,输入app.get(... console.log(res, req);并找到你的变量所在的位置。

Very interesting, for me it worked!

app.get('/search', function (req, res){
   var search = req.query;

   console.log(search, 'of type', typeof search);
   res.send("the query is about the student with name " + search.sname + ' and subject '+search.ssubject );

});

with the form

<form method= 'GET' action="/search" autocomplete="off">
            Student Name:<br>
            <input type="text" name="sname">
            <br>
            Student Subject:<br>
            <input type="text" name="ssubject">
            <br>
            <input type="submit" value="Submit">
            <input type="reset" value="Reset">
        </form>

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