Click here to Skip to main content
15,881,600 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.

JavaScript
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
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900