Create a search feature based on names utilizing Node Express in conjunction with SQL database

After deciding to create an API with a search feature using SQL queries in node express, this is how I structured my code:

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)
            }

        })
    })
})

When testing it on Postman, this is what my setup looked like: https://i.stack.imgur.com/wE1wm.png

The SQL query appears to be correct, but I am unsure how to properly implement the search routing in Node.

Answer №1

If you want to extract path variables, use the following code snippet:

req.params.query

Here's an example of how you can implement this in your code:

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)
            }

        })
    })
})

Answer №2

Give this a shot

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 books WHERE title LIKE '%${search}%' ", (err, rows) => {
        connection.release() // return the connection to pool

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

    })
  })
});

Then access the api at http://localhost:5000/search?q=searchterm, and ensure to watch out for potential sql injection vulnerabilities.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjusting images of various sizes within a single row to fit accordingly

I am faced with a challenge of aligning a set of images on a webpage, each with varying heights, widths, and aspect ratios. My goal is to arrange them in a way that they fit seamlessly across the screen while ensuring their heights are uniform. Adjusting ...

CSS to target every second visible tr element using the :nth-child(2n)

My table has a unique appearance (shown below) thanks to the application of CSS nth-child(2n). tr:nth-child(2n) {background-color: #f0f3f5;} I made some elements hidden on the vID, ID, and MO_Sub tr. <tr style="display:none"> The table's new ...

The Jquery tooltip feature consistently displays the title of the header as the tooltip

Currently, I am utilizing the default Jquery tooltip library, and it functions wonderfully with one exception. In Firefox, the tooltip always displays the title of the page (within <head>). For example: <title>My Title</title></head> ...

Stop zombie.js from loading exclusively third-party resources

During a test, I am using zombie.js to load a page from a local express server. However, the page contains a script element that makes a call to Google Analytics. I want to prevent this external script from loading while allowing other local scripts to run ...

Guide for invoking a servlet via a navigation bar hyperlink and implementing a jQuery feature for smooth scrolling upon clicking

Is there a way to call a servlet from a navigation bar href link and at the same time trigger a jQuery function for smooth scrolling down? I attempted to call the servlet using an onclick href link, it successfully calls the servlet but does not trigger t ...

Whenever I make a move in the Towers of Hanoi javascript game, I always ensure that both towers are updated simultaneously

As I explore the Towers of Hanoi puzzle using JavaScript constructors and prototypes, I encounter issues with my current implementation. Whenever I move a disc from one tower to another, an unintended duplicate appears in a different tower. Additionally, a ...

In vuex, dynamic modules share common data and do not have unique data

Currently, I am facing an issue with an asynchronous API call that returns an array of objects. After receiving this data, I map it to dynamically registered modules in my store. The process looks something like this: dispatch // prior to this dispatch, ...

Achieving the functionality of making only one list item in the navbar bolded upon being clicked using React and Typescript logic

Currently, in my navigation bar, I am attempting to make only the active or clicked list item appear bold when clicked. At the moment, I can successfully achieve this effect; however, when I click on other list items, they also become bolded, while the ori ...

arranging data in various categories with React.js

Can anyone figure out why this code is struggling to properly sort based on columns? sort(key){ this.setState({ [`toggle-${key}`]: !this.state[`toggle-${key}`], data: sortBy(this.state.data, [key], this.state[`toggle-${key}`]).map(v => ...

What could be causing my SectionList to occasionally display only a single section?

I'm facing a problem with the SectionList component where it occasionally fails to display all sections, only rendering the first one. After some debugging, I may have found a solution, but I'm unsure why it resolves the issue. While my page con ...

Troubleshooting a Problem with JSON Array in JavaScript/jQuery - Understanding Undefined Values

Currently, I am fetching data from a JSON file: [ { "video": "video/preroll" }, { "video": "video/areyoupopular" }, { "video": "video/destinationearth" }] I have attempted to use console.log at different stages and encountered an issue when p ...

Stop accidental form submissions on iOS devices by disabling the return button

In my Ionic 3 application running on iOS, I encountered a bug that allows users to submit a form even when the submit button is disabled. Despite trying different solutions from this source, I have not been successful in resolving it. To prevent accidenta ...

Integrating a conditional statement into the existing for loop code to conceal the covers

My goal is to hide the covers after they are clicked using an if statement within the for loop code. I believe this is where it should be placed. Trying to prevent this action from happening. I made an attempt at achieving this but unfortunately couldn&a ...

"Having trouble with Node.js and ExpressJS where the req.files from Multer are coming

Hello, I am currently utilizing multer to retrieve a file from the following form: <form action="/api/pimage" method="POST" enctype="multipart/form-data"> <fieldset> <input type="file" name="profileimage"> <input t ...

Best practices for outputting objects within an array using jQuery and JavaScript

Seeking guidance. I am utilizing a unique jQuery calendar plugin (which appears to be uncommon!) that is fully initialized with JS, without any HTML. In order to include events, you must define each event as an object inside an array: events: [ { ...

Tips for getting information from firestore by implementing a where clause specific to a field within an object?

In my React Native project, I am utilizing Firebase Firestore as the backend database. I have successfully retrieved data from the database using the following code: unsubscribe = firebase.firestore().collection('messages').where('user&apos ...

It appears that the SignalR proxy is not defined

Why is $.connection.connectionhub showing as undefined? I am using webform. <script src="/scripts/jquery-1.6.4.min.js"></script> <!--Reference the SignalR library. --> <script src="/scripts/jquery.signalR-2.2.1.min.js">< ...

There was an issue locating a declaration file for the module 'clarifai'

https://i.stack.imgur.com/PgfqO.jpg I recently encountered a problem after installing the Clarifai API for a face recognition project. Despite my efforts, I have been unable to find a solution. When I hover over "import clarifai," I receive the message: ...

Is there a way to update an array within my class and access its updated output from outside the class?

let arr = [] class Test extends React.Component { handleConvertString = (event) => { let str = this.inputRef.value; let solutions = ['abb','klopp','lopp','hkhk','g','gh','a&apo ...

No testing detected, ending with code zero - NPM and YARN

After installing node js and yarn, I attempted to run an application/script developed by someone else. However, when running the test, I encountered the following message: No tests found, exiting with code 0 Watch Usage › Press f to run only failed tes ...