Ben
Ben

Reputation: 29

How to put HTML text-box form input into Express Route Paramater

I am trying to create a way for users to search through my mongo database via an endpoint like this:

app.get('/search/:input', function(req, res){
  console.log(`get request to: /members/${req.params.input}`);
  var regexValue = '\.*'+req.params.input+'*\.';
  db.collection(myCollection).find({"full_name": {$regex: regexValue, $options: 'i'}}).toArray((err, members) => {
    if(err) return console.log(err)
    console.log(members);
    res.render('search/list', {members: members});
  })
});

I want them to be able to type in a text box and have it go directly do this endpoint. I have a very simple text box like this:

<form action="/search/">
  <input type="text" name="firstname" ><br>
  <input type="submit" value="Submit">
</form>

My problem is I don't know a clean way to get the submitted string from the text box into the request parameter.

Upvotes: 0

Views: 951

Answers (2)

hoangdv
hoangdv

Reputation: 16147

With a Express Route app.get('/search/:input', function(req, res){ then :input is a path paramaters input, but your html form is going to make a GET request /search/?firstname=firstname_value, the request will not maching to the Route.

Use app.get('/search', function(req, res){ instead of your current code, then console.log(get request to: /members/${req.query.firstname}); if you want to use GET method.

(I don't know why log show /members/ ??? while route setting is /search/)

Upvotes: 1

Mr. Ratnadeep
Mr. Ratnadeep

Reputation: 621

You can pass the inputbox value using ajax get method, access the value using req.params.input .Below is the code that I have tried.

app.js

app.get('/:input', function(req, res) {
  console.log(req.params.input);
});

index.ejs

<!DOCTYPE html>
<html>
<head>
  <title>Page Title</title>
</head>
<body>
<input type="text" name="firstname" id="firstname" ><br>
<input type="button" value="search" id="search">
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
    $('#search').click(function(){
        var firstname = $('#firstname').val();
        $.ajax({
            url: "http://localhost:3000/users/"+firstname,
            method: 'get'
        }).done(function() {

        });
    })

</script>

</body>
</html>

Upvotes: 1

Related Questions