Search code examples
javascriptsqlexpresspostman

Make a search function by name using Node Express + SQL


So i wanted to make an API with a search function with SQL queries using node express, this is what my code looked like:

app.get('/search/:query', (req, res) => {
    pool.getConnection((err, connection) => {
        if(err) throw err
        console.log(`connected as id ${connection.threadId}`)

        search = req.query.search
        connection.query("SELECT * FROM beers WHERE name LIKE '%${search}%' ", (err, rows) => {
            connection.release() // return the connection to pool

            if(!err) {
                res.send(rows)
            } else {
                console.log(err)
            }

        })
    })
})

And this is how my postman looked: enter image description here

The SQL query is correct but I dont know how to make the search routing in Node


Solution

  • You can get the parameter from path variables by this

    req.params.query
    

    so your code will be like this

    app.get('/search/:query', (req, res) => {
        pool.getConnection((err, connection) => {
            if(err) throw err
            console.log(`connected as id ${connection.threadId}`)
    
            search = req.params.query
            connection.query("SELECT * FROM beers WHERE name LIKE '%${search}%' ", (err, rows) => {
                connection.release() // return the connection to pool
    
                if(!err) {
                    res.send(rows)
                } else {
                    console.log(err)
                }
    
            })
        })
    })