Start learning free

LESSON 8 OF 58 · FULL-STACK: TWO PROGRAMS, ONE APP

Let the Database Search in JavaScript

Practice

Until now, the search box filtered the eight products in the browser. That works for eight products, but not for eight thousand. Now the given page sends what you type to the server, as in GET /api/products?q=pl, and the database does the searching.

The part of a URL after ? is the query string. Express puts each of its values in req.query, and a value that isn't there is undefined. In SQL, LIKE compares text with a pattern, where % means "any text". So %pl% matches every name with "pl" in it: Plant and Stapler. On another table it looks like this:

db.prepare("SELECT name FROM customers WHERE city LIKE ?").all("%" + text + "%");

The % signs go in the value, and the ? keeps what the visitor typed out of the SQL. An optional filter changes the query only when it is there. It adds one more AND … = ? to the SQL string and one more value to the list, in the same order.

Your server must answer:

page: type "pl", click Search  →  GET /api/products?q=pl  →  2 products: Plant, Stapler
GET /api/products?category=office         →  200  [{"id": 2, "name": "Notebook", …}, {"id": 4, "name": "Pen", …}, {"id": 7, "name": "Stapler", …}]
GET /api/products?q=pl&category=office  →  200  [{"id": 7, "name": "Stapler", "price": 9, "stock": 15}]
GET /api/products?q=%27%20OR%201=1%20--   →  200  []

Your task: in server/app.js, make GET /api/products read q and category from the query string. Build its WHERE with placeholders: name LIKE ? with the value %…%, plus AND category = ? when there is a category.


Assignment
Follow the Coding Tutorial to make the products route in server/app.js search by name and filter by category.


Hint
Each ? needs one value in params, in the same order. ...params spreads those values into .all.


STEP 1 OF 8
    Ctrl + Enter to check

    Fs Search in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free