I have nodejs with a postgres db that i can run queries via API.
If I can curl with localhost:3000/data/ID# and i get data back. The code below is working.
const getDataById = (request, response) => {
const id = parseInt(request.params.id)
pool.query('SELECT * FROM data WHERE id = $1', [id], (error, results) => {
if (error) {
throw error
}
response.status(200).json(results.rows)
})
}
Below is an example of curl with ID# working as expected.
$ curl localhost:3000/data/2
{"id":2,"city":"dallas","data":{"user":"tim","position":"clerk"}}
I need to do the same but use the city name as my parameter.
I need to be able do the same but make the query with column values other than the ID#. For example in the database I can run
data=> SELECT * FROM data WHERE city = 'dallas';
and my results are the same:
{"id":2,"city":"dallas","data":{"user":"tim","position":"clerk"}}
I have tried the using the below but I come up empty on the results:
const getDataCity = (request, response) => {
const city = (request.params.city)
pool.query('SELECT * FROM data WHERE city = $1',[city], (error, results) => {
if (error) {
throw error
}
response.status(200).json(results.rows)
})
}
$ curl localhost:3000/data/dallas
$
Any help or guidance on how I can or should format the query is greatly appreciated.
Cheers
So the fix, actually turned out to be a typo. The problem was PEBCAK. The code was here correct. But in my application; i had something else. It was the following in the app.
response.status(200).json(results.row)
So I changed it to (results.rows)
like it should have been and magically things work, now :)
const getDataCity = (request, response) => {
const city = (request.params.city)
pool.query('SELECT * FROM data WHERE city = $1',[city], (error, results) => {
if (error) {
console.log('error:', error)
}
response.status(200).json(results.rows)
})
}
$ curl localhost:3000/data/dallas
$ {"id":2,"city":"dallas","data":{"user":"tim","position":"clerk"}}
I also did stop throwing the error and logged it; because it is good practice, thanks @Bergi for that call out.
The actual fix is making sure you review all code and catch things.