Hello everyone. I have been going through an online course about creating a back-end of a web app with Node.js and SQlite database. Node.js codes alone worked perfectly well. In a database tutorial alone everything worked well. But, when I combined the two and started passing SQL commands from my Node.js API to a database that is where the problems started.
It is a simple API that has to return quotes from a database based on user (browser) input. When I tested it, it did show the entire list of quotes on .../quotes (which is expected),but when I entered .../quotes?year=1910 hoping to get a quote for which a year column has value 1910 from my database, for some reason I got an empty json (i.e. [])object. Excuse my explanation, I tried to give as much details as possible. Here is the code down below.
app.get('/quotes', function(req, res){
if(req.query.year){
db.all('SELECT * FROM quotes WHERE year = ?', [req.query.year], function(err, rows){
if(err){
res.send(err.message);
}
else{
console.log("Return a list of quotes from the year: " + req.query.year);
res.json(rows);
}
});
}
else{
db.all('SELECT * FROM quotes', function processRows(err, rows){
if(err){
res.send(err.message);
}
else{
for( var i = 0; i < rows.length; i++){
console.log(rows[i].quote);
}
res.json(rows);
}
});
}
});
What I have tried:
I have double checked that a record with year 1910 exist in a database
I have double checked that all necessary node.js modules are installed for the project
I have double checked the headers in my node.js code