soda
soda

Reputation: 523

I am sending a sqlite3 query result through node js to the browser as json

var express = require('express');
var app = express();
var sqlite3 = require('sqlite3');

var db = new sqlite3.Database('Items.db');




app.listen(3000, function(){
    console.log('Server is listening on port 3000');
});


app.get('/', function(request, response){

db.all("SELECT * FROM Items WHERE id>1", function(err,rows,fields) {

    console.log(rows);
    console.log('This function will return a list of all stored items from database ' + rows);
    response.setHeader('Content-Type','application/json')
    response.send(JSON.stringify(rows));


});

});

But the browser is not any anything.

On logging the rows to terminal it shows undefined.

terminal screenshot

I think the rows is not fetching results from the db.I think there might be problem in the path where db is located. Can you tell where to place the db file?? Or if there's any other problem??

Upvotes: 2

Views: 1915

Answers (1)

Jemi Salo
Jemi Salo

Reputation: 3751

Likely cause

You're trying to open Items.db in the same directory as server.js. There is no file named Items.db in the directory, so a new empty database Items.db is created.

Change

var db = new sqlite3.Database('Items.db');

to

var db = new sqlite3.Database('relative_path_to/Items.db');

Where relative_path_to is the relative path from server.js to Items.db.

You can get the same result by moving Inputs.db to the same directory as server.js.

Alternative cause

Items.db has no table Items.

Make sure Items.db has a table with that name.

sqlite3 Items.db
sqlite> CREATE TABLE IF NOT EXISTS Items (id INTEGER);
sqlite> .exit

Upvotes: 1

Related Questions