skip to Main Content

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

2

Answers


  1. You can try this

    app.get('/search', async function(req, res) {
        let page = req.query.page;
        let limit = req.query.limit;
        let search= req.query.q;
        //
        pool.getConnection((err, connection) => {
        if(err) throw err
        console.log(`connected as id ${connection.threadId}`)
    
        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 call api like this http://localhost:5000/search?q=yoursearchterm, also check for possible sql injection issue.

    Login or Signup to reply.
  2. 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)
                }
    
            })
        })
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search