SlideShare a Scribd company logo
Node and SQLLite
SQLite Database with Node
https://www.udemy.com/node-
database/?couponCode=SLIDESHARE
INSTRUCTOR:
LAURENCE SVEKIS
Course instructor : Laurence Svekis
- Over 300 courses in technology and
web applications.
- 20 years of JavaScript web
programming experience
- 500,000+ students across multiple
platforms
- Digital instructor since 2002
READY TO HELP YOU LEARN and
ANSWER ANY questions you may
have.
Windows Terminal
Windows - https://cmder.net/ or use the
command prompt terminal
Launch the Command Prompt - use the Run
window or press the Win + R keys on your
keyboard. Then, type cmd and press Enter.
List current directory of files - dir
Change directory to D drive - cd D:
Change directory down one level - cd..
Change directory to folder by name - cd folder
Make new folder - mkdir folderName
Get help - help
Mac Terminal
Open Terminal by pressing Command+Space or
select terminal in the applications list.
List current directory of files - ls
Change directory to D drive - cd D:
Change directory down one level - cd..
Change directory to folder by name - cd folder
Make new folder - mkdir folderName
Get help - help
Command Line Launch
One node is installed check to see version
installed. Type node -v
Open your editor and create a js file that
contains console.log('Hello World'); save
it as test.js
In the terminal type node test.js and watch
for a result. What gets returned?
NPM - check if its installed npm -v latest
version install npm install npm@latest -g
Create app js file
Create a main app js file to run your node application.
touch app.js
Install setup Node and Express
https://nodejs.org/en/download/
Select the platform and install
Setup of Localhost machine
https://expressjs.com/
In the terminal
node -v
npm install express --save
Npm package.json
Install all the dependencies for your project. Create
a package.json file.
You can also install packages using
Optional flags
--save - installs and adds to the package.json
--save-dev - installs and adds to the package.json
under devDependencies.
Updating packages - check all packages or specific
package.
npm install <package-name>
npm update
npm update <package-name>
Npm install Packages
Default its installed under the current tree. Npm init
to create package.json
Also adds the dependencies to the package.json
file in current folder.
Global installations of the package can be done by
adding the flag -g. Will install package to global
location.
Get global root folder.
npm init
npm install -g <package-name>
npm root -g
Npm uninstall Packages
Default its installed under the current tree.
Also adds the dependencies to the package.json
file in current folder.
Global installations of the package can be done by
adding the flag -g. Will install package to global
location.
Get global root folder.
npm uninstall <package-name>
npm install -g <package-name>
npm root -g
Setup - Local Server
Run app.js and Open Browser to localhost:8080 -
port with http path.
Assign variable to app object.
Open http://localhost:8080/ in your browser.
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('ready')
})
app.listen(8080, function () {
console.log('Server ready')
})
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('ready')
})
const server = app.listen(8080, function () {
console.log('Server ready')
})
node app.js
NodeMon
Nodemon is a utility that will monitor for any
changes in your source and automatically restart
your server. Perfect for development.
npm install -g nodemon
https://nodemon.io/
Run it
nodemon app.js
** make some changes no more node restart
typing ;)
Setup - Local Express Server
Run app.js and Open Browser to localhost:8080 -
port with http path.
Assign variable to app object.
Open http://localhost:8080/ in your browser.
const express = require('express');
const app = express();
const port = 8080;
const server = app.listen(port, function () {
console.log('Server ready')
})
app.get('/', function (req, res) {
res.json({
"status": "ready"
})
})
app.use(function (req, res) {
res.status(404);
});
nodemon app.js
Install SQLlite and MD5 for hash of passwords
https://www.npmjs.com/package/sqlite3
SQLite is a relational database management
system contained in a C library. In contrast to
many other database management systems,
SQLite is not a client–server database engine.
Rather, it is embedded into the end program.
https://www.sqlite.org/about.html
npm install sqlite3
a JavaScript function for hashing messages with
MD5.
https://www.npmjs.com/package/md5
npm install md5
Setup - Database and create Table
Create a new js file to setup a database.
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./db/user.db');
db.run('CREATE TABLE users(id INTEGER PRIMARY KEY
AUTOINCREMENT,first,last,email,password)');
db.close();
touch dbsetup.js
mkdir db
node dbsetup.js
touch insert.js
touch insert.js
Create a new js file to insert to the database.
Add to database new users table.
Catch the errors
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./db/user.db');
let sql = 'INSERT INTO users (first,last,email,password) VALUES
("Laurence", "Svekis", "gappscourses@gmail.com", "password")';
db.run(sql, [], function(err) {
if (err) {
return console.log(err.message);
}
console.log(`Rowid ${this.lastID}`);
});
db.close();
Database as module
Setup the db.js file as the database connection,
useful if you need to change file locations.
Use a module
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('./db/user.db');
module.exports = db;
**** On app.js add
const db = require("./db.js")
touch db.js
Query Database for users
Querying all rows with all() method -
Will output all the contents of the database.
const sqlite3 = require('sqlite3').verbose();
const md5 = require('md5');
const db = new sqlite3.Database('./db/user.db');
module.exports = db;
**** On app.js add
const db = require("./db.js")
const db = require("./db.js")
const query = "select * from users";
db.all(query, function (err, rows) {
if (err) {
throw err;
}
rows.forEach(function (row) {
console.log(row);
});
});
List users in web page
Using express setup a new route for users const express = require('express');
const app = express();
const port = 8080;
const db = require("./db.js")
const server = app.listen(port, function () {
console.log('Server ready')
})
app.get('/users', function (req, res) {
const query = "select * from users";
db.all(query, function (err, rows) {
if (err) {
throw err;
}
res.json({
"data": rows
});
});
})
app.get('/', function (req, res) {
res.json({
"status": "ready"
})
})
app.use(function (req, res) {
res.status(404);
});
List get users by id
In the browser go to the users folder and add an
id value at the end.
app.get("/users/:id", function (req, res) {
const query = "select * from users where id = ?"
const params = [req.params.id]
db.get(query, params, function (err, row) {
if (err) {
throw err;
}
res.json({
"data": row
})
});
});
Create new User
Create the browser side add.html file with a form
for inputs and event listener to send request.
For node setup install of body-parser
https://github.com/expressjs/body-parser body
parsing middleware
<form>
<input type='text' name='first' value='Laurence'>
<input type='text' name='last' value='Svekis'>
<input type='text' name='email' value='example@example.com'>
<input type='text' name='password' value='secret'>
<input type='submit'> </form>
<script>
const myForm = document.querySelector('form');
const inputs = document.querySelectorAll('input');
myForm.addEventListener("submit", function (evt) {
evt.preventDefault();
fetch('/adder', {
method: 'POST'
, body: JSON.stringify({
first: inputs[0].value
, last: inputs[1].value
, email: inputs[2].value
, password: inputs[3].value
, })
, headers: {
"Content-Type": "application/json"
}
}).then(function (response) {
return response.json()
}).then(function (body) {
console.log(body);
});
});
</script>
npm install body-parser
Node get new user data
Submit the form and check for request data from
the body in the console.
const express = require('express');
const app = express();
const port = 8080;
const db = require("./db.js")
const server = app.listen(port, function () {
console.log('Server ready')
})
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:true }));
app.post('/adder', function (req, res) {
console.log(req.body);
console.log('req.body.first', req.body['first']);
})
Add new user to database
Update post to insert into database.
You can go to users to list all
http://localhost:8080/users
const express = require('express');
const app = express();
const port = 8080;
const db = require("./db.js")
const server = app.listen(port, function () {
console.log('Server ready')
})
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:true }));
app.post('/adder', function (req, res) {
console.log(req.body);
let insert = 'INSERT INTO users(first,last,email,password) VALUES (?,?,?,?)'
db.run(insert, [req.body['first'], req.body['last'], req.body['email'], req.body['password']],
function (err, row) {
if (err) {
throw err;
}
res.json({
"data": this.lastID
})
});
})
app.use(function (req, res) {
res.status(404);
});
Full Source Code app.js
app.get('/', function (req, res) {
res.json({"status": "ready"})
})
app.get('/new', function (req, res) {
res.sendFile(__dirname + '/add.html');
})
app.post('/adder', function (req, res) {
console.log(req.body);
let insert = 'INSERT INTO users(first,last,email,password) VALUES (?,?,?,?)'
db.run(insert, [req.body['first'], req.body['last'], req.body['email'], req.body['password']],
function (err, row) {
if (err) {throw err;}
res.json({"data": this.lastID })
});
})
app.use(function (req, res) {
res.status(404);
});
const express = require('express');
const app = express();
const port = 8080;
const db = require("./db.js")
const server = app.listen(port, function () {console.log('Server ready')})
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/users', function (req, res) {
const query = "select * from users";
const params = [];
db.all(query, params, function (err, rows) {
if (err) {throw err;}
res.json({"data": rows});
});
})
app.get("/users/:id", function (req, res) {
const query = "select * from users where id = ?"
const params = [req.params.id]
db.get(query, params, function (err, row) {
if (err) {throw err;}
res.json({ "data": row })
});
});
Full Source Code other files
<!-- add.html -->
<form><input type='text' name='first' value='Laurence'><input type='text' name='last'
value='Svekis'><input type='text' name='email' value='example@example.com'><input
type='text' name='password' value='secret'><input type='submit'> </form>
<script>
const myForm = document.querySelector('form');
const inputs = document.querySelectorAll('input');
myForm.addEventListener("submit", function (evt) {
evt.preventDefault();
fetch('/adder', {
method: 'POST'
, body: JSON.stringify({first: inputs[0].value, last: inputs[1].value, email:
inputs[2].value, password: inputs[3].value })
, headers: {"Content-Type": "application/json" }
}).then(function (response) {
return response.json()
}).then(function (body) {
console.log(body);
});
});
</script>
//db.js
const sqlite3 = require('sqlite3').verbose()
const md5 = require('md5')
const db = new sqlite3.Database('./db/user.db');
module.exports = db
//dbsetup.js
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./db/user.db');
db.run('CREATE TABLE users(id INTEGER PRIMARY KEY
AUTOINCREMENT,first,last,email,password)');
db.close();
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./db/user.db');
let sql = 'INSERT INTO users (first,last,email,password) VALUES ("Laurence", "Svekis",
"gappscourses@gmail.com", "password")';
db.run(sql, [], function(err) {
if (err) {
return console.log(err.message);
}
console.log(`Rowid ${this.lastID}`);
});
db.close();
Congratulations on completing the section
Course instructor : Laurence Svekis -
providing online training to over
500,000 students across hundreds of
courses and many platforms.
Find out more about my courses at
http://www.discoveryvip.com/

More Related Content

PPTX
Java Server Pages(jsp)
PPT
Asp.net.
PPTX
Introduction to HTML5 and CSS3 (revised)
PPT
Jsp ppt
PPTX
Css selectors
PPTX
Spring boot
PPTX
PPTX
PHP Cookies and Sessions
Java Server Pages(jsp)
Asp.net.
Introduction to HTML5 and CSS3 (revised)
Jsp ppt
Css selectors
Spring boot
PHP Cookies and Sessions

What's hot (20)

PDF
Programmation Shell Script
PDF
jQuery for beginners
PPT
Web Applications and Deployment
PDF
Formation Spring Avancé gratuite par Ippon 2014
PPTX
Html5
PPTX
Angular overview
PPTX
Hibernate ppt
PPTX
Introduction to asp.net
PPTX
Cookie & Session In ASP.NET
PPTX
Server Side Programming
PPTX
Express js
PPTX
Event In JavaScript
PDF
Support distributed computing and caching avec hazelcast
PDF
JavaScript - Chapter 15 - Debugging Techniques
PDF
Nuxt.JS Introdruction
PDF
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
PPTX
Master page in Asp.net
PPT
Serialization/deserialization
PDF
Angular - Chapter 4 - Data and Event Handling
PDF
Java notes
Programmation Shell Script
jQuery for beginners
Web Applications and Deployment
Formation Spring Avancé gratuite par Ippon 2014
Html5
Angular overview
Hibernate ppt
Introduction to asp.net
Cookie & Session In ASP.NET
Server Side Programming
Express js
Event In JavaScript
Support distributed computing and caching avec hazelcast
JavaScript - Chapter 15 - Debugging Techniques
Nuxt.JS Introdruction
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Master page in Asp.net
Serialization/deserialization
Angular - Chapter 4 - Data and Event Handling
Java notes
Ad

Similar to Local SQLite Database with Node for beginners (20)

PDF
Introduction to Node js for beginners + game project
PPT
RESTful API In Node Js using Express
PPT
nodejs_at_a_glance, understanding java script
PPT
nodejs_at_a_glance.ppt
PDF
Build Web Apps using Node.js
PPTX
U4-01-Node JS.pptxweasrdtfyhg[]"Piuytrhedfyguhijokpl
PPTX
SenchaCon 2016: Advanced Techniques for Buidling Ext JS Apps with Electron - ...
PDF
Node js introduction
PDF
Node.js in action
PPT
nodejs tutorial foor free download from academia
PPTX
NodeJs
KEY
Node.js basics
PDF
Having Fun with Play
PPTX
Nodejs.meetup
PDF
Rails 3 overview
PDF
May The Nodejs Be With You
PDF
Step By Step Guide For Buidling Simple Struts App
PPTX
TO Hack an ASP .NET website?
PPTX
Hack ASP.NET website
PPTX
Introducing Node.js in an Oracle technology environment (including hands-on)
Introduction to Node js for beginners + game project
RESTful API In Node Js using Express
nodejs_at_a_glance, understanding java script
nodejs_at_a_glance.ppt
Build Web Apps using Node.js
U4-01-Node JS.pptxweasrdtfyhg[]"Piuytrhedfyguhijokpl
SenchaCon 2016: Advanced Techniques for Buidling Ext JS Apps with Electron - ...
Node js introduction
Node.js in action
nodejs tutorial foor free download from academia
NodeJs
Node.js basics
Having Fun with Play
Nodejs.meetup
Rails 3 overview
May The Nodejs Be With You
Step By Step Guide For Buidling Simple Struts App
TO Hack an ASP .NET website?
Hack ASP.NET website
Introducing Node.js in an Oracle technology environment (including hands-on)
Ad

More from Laurence Svekis ✔ (20)

PDF
Quiz JavaScript Objects Learn more about JavaScript
PDF
JavaScript Lessons 2023 V2
PDF
JavaScript Lessons 2023
PDF
Top 10 Linkedin Tips Guide 2023
PDF
JavaScript Interview Questions 2023
PDF
Code examples javascript ebook
PDF
Javascript projects Course
PDF
10 java script projects full source code
PDF
Chrome DevTools Introduction 2020 Web Developers Guide
PDF
Brackets code editor guide
PDF
Web hosting get start online
PDF
JavaScript guide 2020 Learn JavaScript
PDF
Web hosting Free Hosting
PDF
Web development resources brackets
PPTX
Google Apps Script for Beginners- Amazing Things with Code
PPTX
JavaScript DOM - Dynamic interactive Code
PPTX
JavaScript Advanced - Useful methods to power up your code
PPTX
Monster JavaScript Course - 50+ projects and applications
PPTX
JavaScript Objects and OOP Programming with JavaScript
PPTX
JavaScript Core fundamentals - Learn JavaScript Here
Quiz JavaScript Objects Learn more about JavaScript
JavaScript Lessons 2023 V2
JavaScript Lessons 2023
Top 10 Linkedin Tips Guide 2023
JavaScript Interview Questions 2023
Code examples javascript ebook
Javascript projects Course
10 java script projects full source code
Chrome DevTools Introduction 2020 Web Developers Guide
Brackets code editor guide
Web hosting get start online
JavaScript guide 2020 Learn JavaScript
Web hosting Free Hosting
Web development resources brackets
Google Apps Script for Beginners- Amazing Things with Code
JavaScript DOM - Dynamic interactive Code
JavaScript Advanced - Useful methods to power up your code
Monster JavaScript Course - 50+ projects and applications
JavaScript Objects and OOP Programming with JavaScript
JavaScript Core fundamentals - Learn JavaScript Here

Recently uploaded (20)

PDF
Mega Projects Data Mega Projects Data
PDF
The Rise of Impact Investing- How to Align Profit with Purpose
PPTX
climate analysis of Dhaka ,Banglades.pptx
PPTX
Global journeys: estimating international migration
PPTX
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pptx
PDF
22.Patil - Early prediction of Alzheimer’s disease using convolutional neural...
PPT
Chapter 2 METAL FORMINGhhhhhhhjjjjmmmmmmmmm
PPTX
The THESIS FINAL-DEFENSE-PRESENTATION.pptx
PPTX
Introduction to Knowledge Engineering Part 1
PDF
Master Databricks SQL with AccentFuture – The Future of Data Warehousing
PPTX
Supervised vs unsupervised machine learning algorithms
PDF
Launch Your Data Science Career in Kochi – 2025
PPTX
DISORDERS OF THE LIVER, GALLBLADDER AND PANCREASE (1).pptx
PDF
Taxes Foundatisdcsdcsdon Certificate.pdf
PPT
Quality review (1)_presentation of this 21
PPTX
Introduction to Basics of Ethical Hacking and Penetration Testing -Unit No. 1...
PDF
.pdf is not working space design for the following data for the following dat...
PPTX
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
PPTX
Data_Analytics_and_PowerBI_Presentation.pptx
Mega Projects Data Mega Projects Data
The Rise of Impact Investing- How to Align Profit with Purpose
climate analysis of Dhaka ,Banglades.pptx
Global journeys: estimating international migration
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pptx
22.Patil - Early prediction of Alzheimer’s disease using convolutional neural...
Chapter 2 METAL FORMINGhhhhhhhjjjjmmmmmmmmm
The THESIS FINAL-DEFENSE-PRESENTATION.pptx
Introduction to Knowledge Engineering Part 1
Master Databricks SQL with AccentFuture – The Future of Data Warehousing
Supervised vs unsupervised machine learning algorithms
Launch Your Data Science Career in Kochi – 2025
DISORDERS OF THE LIVER, GALLBLADDER AND PANCREASE (1).pptx
Taxes Foundatisdcsdcsdon Certificate.pdf
Quality review (1)_presentation of this 21
Introduction to Basics of Ethical Hacking and Penetration Testing -Unit No. 1...
.pdf is not working space design for the following data for the following dat...
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
Data_Analytics_and_PowerBI_Presentation.pptx

Local SQLite Database with Node for beginners

  • 1. Node and SQLLite SQLite Database with Node https://www.udemy.com/node- database/?couponCode=SLIDESHARE
  • 2. INSTRUCTOR: LAURENCE SVEKIS Course instructor : Laurence Svekis - Over 300 courses in technology and web applications. - 20 years of JavaScript web programming experience - 500,000+ students across multiple platforms - Digital instructor since 2002 READY TO HELP YOU LEARN and ANSWER ANY questions you may have.
  • 3. Windows Terminal Windows - https://cmder.net/ or use the command prompt terminal Launch the Command Prompt - use the Run window or press the Win + R keys on your keyboard. Then, type cmd and press Enter. List current directory of files - dir Change directory to D drive - cd D: Change directory down one level - cd.. Change directory to folder by name - cd folder Make new folder - mkdir folderName Get help - help
  • 4. Mac Terminal Open Terminal by pressing Command+Space or select terminal in the applications list. List current directory of files - ls Change directory to D drive - cd D: Change directory down one level - cd.. Change directory to folder by name - cd folder Make new folder - mkdir folderName Get help - help
  • 5. Command Line Launch One node is installed check to see version installed. Type node -v Open your editor and create a js file that contains console.log('Hello World'); save it as test.js In the terminal type node test.js and watch for a result. What gets returned? NPM - check if its installed npm -v latest version install npm install npm@latest -g
  • 6. Create app js file Create a main app js file to run your node application. touch app.js
  • 7. Install setup Node and Express https://nodejs.org/en/download/ Select the platform and install Setup of Localhost machine https://expressjs.com/ In the terminal node -v npm install express --save
  • 8. Npm package.json Install all the dependencies for your project. Create a package.json file. You can also install packages using Optional flags --save - installs and adds to the package.json --save-dev - installs and adds to the package.json under devDependencies. Updating packages - check all packages or specific package. npm install <package-name> npm update npm update <package-name>
  • 9. Npm install Packages Default its installed under the current tree. Npm init to create package.json Also adds the dependencies to the package.json file in current folder. Global installations of the package can be done by adding the flag -g. Will install package to global location. Get global root folder. npm init npm install -g <package-name> npm root -g
  • 10. Npm uninstall Packages Default its installed under the current tree. Also adds the dependencies to the package.json file in current folder. Global installations of the package can be done by adding the flag -g. Will install package to global location. Get global root folder. npm uninstall <package-name> npm install -g <package-name> npm root -g
  • 11. Setup - Local Server Run app.js and Open Browser to localhost:8080 - port with http path. Assign variable to app object. Open http://localhost:8080/ in your browser. const express = require('express') const app = express() app.get('/', function (req, res) { res.send('ready') }) app.listen(8080, function () { console.log('Server ready') }) const express = require('express') const app = express() app.get('/', function (req, res) { res.send('ready') }) const server = app.listen(8080, function () { console.log('Server ready') }) node app.js
  • 12. NodeMon Nodemon is a utility that will monitor for any changes in your source and automatically restart your server. Perfect for development. npm install -g nodemon https://nodemon.io/ Run it nodemon app.js ** make some changes no more node restart typing ;)
  • 13. Setup - Local Express Server Run app.js and Open Browser to localhost:8080 - port with http path. Assign variable to app object. Open http://localhost:8080/ in your browser. const express = require('express'); const app = express(); const port = 8080; const server = app.listen(port, function () { console.log('Server ready') }) app.get('/', function (req, res) { res.json({ "status": "ready" }) }) app.use(function (req, res) { res.status(404); }); nodemon app.js
  • 14. Install SQLlite and MD5 for hash of passwords https://www.npmjs.com/package/sqlite3 SQLite is a relational database management system contained in a C library. In contrast to many other database management systems, SQLite is not a client–server database engine. Rather, it is embedded into the end program. https://www.sqlite.org/about.html npm install sqlite3 a JavaScript function for hashing messages with MD5. https://www.npmjs.com/package/md5 npm install md5
  • 15. Setup - Database and create Table Create a new js file to setup a database. const sqlite3 = require('sqlite3').verbose(); let db = new sqlite3.Database('./db/user.db'); db.run('CREATE TABLE users(id INTEGER PRIMARY KEY AUTOINCREMENT,first,last,email,password)'); db.close(); touch dbsetup.js mkdir db node dbsetup.js touch insert.js touch insert.js Create a new js file to insert to the database. Add to database new users table. Catch the errors const sqlite3 = require('sqlite3').verbose(); let db = new sqlite3.Database('./db/user.db'); let sql = 'INSERT INTO users (first,last,email,password) VALUES ("Laurence", "Svekis", "[email protected]", "password")'; db.run(sql, [], function(err) { if (err) { return console.log(err.message); } console.log(`Rowid ${this.lastID}`); }); db.close();
  • 16. Database as module Setup the db.js file as the database connection, useful if you need to change file locations. Use a module const sqlite3 = require('sqlite3').verbose(); const db = new sqlite3.Database('./db/user.db'); module.exports = db; **** On app.js add const db = require("./db.js") touch db.js
  • 17. Query Database for users Querying all rows with all() method - Will output all the contents of the database. const sqlite3 = require('sqlite3').verbose(); const md5 = require('md5'); const db = new sqlite3.Database('./db/user.db'); module.exports = db; **** On app.js add const db = require("./db.js") const db = require("./db.js") const query = "select * from users"; db.all(query, function (err, rows) { if (err) { throw err; } rows.forEach(function (row) { console.log(row); }); });
  • 18. List users in web page Using express setup a new route for users const express = require('express'); const app = express(); const port = 8080; const db = require("./db.js") const server = app.listen(port, function () { console.log('Server ready') }) app.get('/users', function (req, res) { const query = "select * from users"; db.all(query, function (err, rows) { if (err) { throw err; } res.json({ "data": rows }); }); }) app.get('/', function (req, res) { res.json({ "status": "ready" }) }) app.use(function (req, res) { res.status(404); });
  • 19. List get users by id In the browser go to the users folder and add an id value at the end. app.get("/users/:id", function (req, res) { const query = "select * from users where id = ?" const params = [req.params.id] db.get(query, params, function (err, row) { if (err) { throw err; } res.json({ "data": row }) }); });
  • 20. Create new User Create the browser side add.html file with a form for inputs and event listener to send request. For node setup install of body-parser https://github.com/expressjs/body-parser body parsing middleware <form> <input type='text' name='first' value='Laurence'> <input type='text' name='last' value='Svekis'> <input type='text' name='email' value='[email protected]'> <input type='text' name='password' value='secret'> <input type='submit'> </form> <script> const myForm = document.querySelector('form'); const inputs = document.querySelectorAll('input'); myForm.addEventListener("submit", function (evt) { evt.preventDefault(); fetch('/adder', { method: 'POST' , body: JSON.stringify({ first: inputs[0].value , last: inputs[1].value , email: inputs[2].value , password: inputs[3].value , }) , headers: { "Content-Type": "application/json" } }).then(function (response) { return response.json() }).then(function (body) { console.log(body); }); }); </script> npm install body-parser
  • 21. Node get new user data Submit the form and check for request data from the body in the console. const express = require('express'); const app = express(); const port = 8080; const db = require("./db.js") const server = app.listen(port, function () { console.log('Server ready') }) const bodyParser = require("body-parser"); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended:true })); app.post('/adder', function (req, res) { console.log(req.body); console.log('req.body.first', req.body['first']); })
  • 22. Add new user to database Update post to insert into database. You can go to users to list all http://localhost:8080/users const express = require('express'); const app = express(); const port = 8080; const db = require("./db.js") const server = app.listen(port, function () { console.log('Server ready') }) const bodyParser = require("body-parser"); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended:true })); app.post('/adder', function (req, res) { console.log(req.body); let insert = 'INSERT INTO users(first,last,email,password) VALUES (?,?,?,?)' db.run(insert, [req.body['first'], req.body['last'], req.body['email'], req.body['password']], function (err, row) { if (err) { throw err; } res.json({ "data": this.lastID }) }); }) app.use(function (req, res) { res.status(404); });
  • 23. Full Source Code app.js app.get('/', function (req, res) { res.json({"status": "ready"}) }) app.get('/new', function (req, res) { res.sendFile(__dirname + '/add.html'); }) app.post('/adder', function (req, res) { console.log(req.body); let insert = 'INSERT INTO users(first,last,email,password) VALUES (?,?,?,?)' db.run(insert, [req.body['first'], req.body['last'], req.body['email'], req.body['password']], function (err, row) { if (err) {throw err;} res.json({"data": this.lastID }) }); }) app.use(function (req, res) { res.status(404); }); const express = require('express'); const app = express(); const port = 8080; const db = require("./db.js") const server = app.listen(port, function () {console.log('Server ready')}) const bodyParser = require("body-parser"); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.get('/users', function (req, res) { const query = "select * from users"; const params = []; db.all(query, params, function (err, rows) { if (err) {throw err;} res.json({"data": rows}); }); }) app.get("/users/:id", function (req, res) { const query = "select * from users where id = ?" const params = [req.params.id] db.get(query, params, function (err, row) { if (err) {throw err;} res.json({ "data": row }) }); });
  • 24. Full Source Code other files <!-- add.html --> <form><input type='text' name='first' value='Laurence'><input type='text' name='last' value='Svekis'><input type='text' name='email' value='[email protected]'><input type='text' name='password' value='secret'><input type='submit'> </form> <script> const myForm = document.querySelector('form'); const inputs = document.querySelectorAll('input'); myForm.addEventListener("submit", function (evt) { evt.preventDefault(); fetch('/adder', { method: 'POST' , body: JSON.stringify({first: inputs[0].value, last: inputs[1].value, email: inputs[2].value, password: inputs[3].value }) , headers: {"Content-Type": "application/json" } }).then(function (response) { return response.json() }).then(function (body) { console.log(body); }); }); </script> //db.js const sqlite3 = require('sqlite3').verbose() const md5 = require('md5') const db = new sqlite3.Database('./db/user.db'); module.exports = db //dbsetup.js const sqlite3 = require('sqlite3').verbose(); let db = new sqlite3.Database('./db/user.db'); db.run('CREATE TABLE users(id INTEGER PRIMARY KEY AUTOINCREMENT,first,last,email,password)'); db.close(); const sqlite3 = require('sqlite3').verbose(); let db = new sqlite3.Database('./db/user.db'); let sql = 'INSERT INTO users (first,last,email,password) VALUES ("Laurence", "Svekis", "[email protected]", "password")'; db.run(sql, [], function(err) { if (err) { return console.log(err.message); } console.log(`Rowid ${this.lastID}`); }); db.close();
  • 25. Congratulations on completing the section Course instructor : Laurence Svekis - providing online training to over 500,000 students across hundreds of courses and many platforms. Find out more about my courses at http://www.discoveryvip.com/