Building an e-Commerce website with Node – Part 36 – Create routes for searching in Node.js

We are going to create two new routes for searching. Open main.js file and type the following code.'/search', function(req, res, next) {
  res.redirect('/search?q=' + req.body.q);

router.get('/search', function(req, res, next) {
  if (req.query.q) {{
      query_string: { query: req.query.q}
    }, function(err, results) {
      if (err) return next(err);
      var data = {
        return hit;
      res.render('main/search-result', {
        query: req.query.q,
        data: data

The first router basically says: go to a search route and pass the message along which is “req.body.q”. Post method sends data to the server.

The second router is a GET which means it gets data from the server. The only way for us to retrieve data from the server is to use req.query.g. The allows us to search in the Elasticsearch replica set for what we need to find.

Now, let’s create the search-result.ejs page under the views/main folder then type in the following code.

<% layout('layout') -%>

<% if (data.length === 0)  { %>
  <h3>Search not found</h3>
<% } else {%>
  <h3>Results for <%= query %></h3>
  <div class="container">
  <div class="row">
    <% for (var i = 0; i < data.length; i++) { %>
    <div class="col-md-4">
      <a href="/product/<%= data[i]._source._id %>">
        <div class="thumbnail">
          <img src="<%= data[i]._source.image %>">
          <div class="caption">
            <h3><%= data[i] %></h3>
            <p><%= data[i] %></h3>
            <p>$<%= data[i]._source.price %></p>
    <% } %>

<% } %>

Now, we need to add a search box in the navigation bar so users can use it to search for things they are interested in. Open the navbar.ejs file which is under the views/main/partials folder and type in the following code.

    <form class="navbar-form navbar-left" method="post" action="/search">
      <div class="form-group">
        <input type="text" name="q" class="form-control" placeholder="Search...">
        <button type="submit" class="btn btn-default">Submit</button>

Now we have a search bar that actually works on our website. Go ahead and test it. Don’t forget to start both servers, Node and Elasticsearch.

Leave a Reply