I am trying to make a query from my database through the url, but the response just returns all my persons.
exports.getPersonByName = async (req, res) => {
const query = req.query.q
try{
const person = await pool.query('SELECT * FROM person WHERE firstname LIKE $1', [query])
res.status(200).json(person)
} catch(error) {
res.status(500).json({ message: error.message })
}
}
There are two problems with your implementation.
urlencoded middleware in the server.js file (Add it after the app.use(express.json()) line):app.use(express.urlencoded({ extended: true }));
getPersonByName method in person.route.js.
You don't need to specify query parameters in the route itself.
Currently, your GET /person route is used by the getAllPersons function, so you have two options:getAllPersons and getPersonByName functions under the same path GET /person and retrieve the parameter if present.You will be keeping only the getAllPersons route and functions and handle the q parameter in there
exports.getAllPersons = async (req, res) => {
const query = req.query.q || '';
try {
const person = await pool.query(
'SELECT * FROM person WHERE firstname LIKE $1',
[query]
);
res.status(200).json(person);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
getPersonByName, for example:router.get('/byname', controller.getPersonByName)
And send your requests to /person/byname?q=Example (Keeping the getPersonByName and getAllPersons methods as defined)