Hi:
I am trying to get an understanding of server side programming. I am trying to test my POST Api with POSTMAN.
1. created server.js
2. created database.js
3. ran "npm init -y"
4. ran "npm install express"
5. ran "npm install sqlite3"
6. ran "node server.js"
I have included the coding of 1. and 2. I have attached two screen shots of VB Terminal and POSTMAN. POSTMAN gives an error. Thanks for your helps.
I am trying to get an understanding of server side programming. I am trying to test my POST Api with POSTMAN.
1. created server.js
2. created database.js
3. ran "npm init -y"
4. ran "npm install express"
5. ran "npm install sqlite3"
6. ran "node server.js"
I have included the coding of 1. and 2. I have attached two screen shots of VB Terminal and POSTMAN. POSTMAN gives an error. Thanks for your helps.
JavaScript:
var express = require("express");
var app = express();
var db = require("./database.js");
var bodyParser = require("body-parser");
const { request, response } = require("express");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
let HTTP_PORT = 8081;
app.listen(HTTP_PORT,()=>{
console.log("Server is running on %PORT%".replace("%PORT%", HTTP_PORT))
});
app.post("/api/customer1/", (req, res, next) => {
try {
var errors = []
if (!req.body) {
errors.push("An invalid input");
}
const { name,
address,
email,
dateOfBirth,
gender,
age,
cardHolderName,
cardNumber,
expiryDate,
cvv,
timeStamp
} = req.body;
var sql = 'INSERT INTO customer (name, address, email, dateOfBirth, gender, age, cardHolderName, cardNumber, expiryDate, cvv, timeStamp) VALUES (?,?,?,?,?,?,?,?,?,?, ?)'
var params = [name, address, email, dateOfBirth, gender, age, cardHolderName, cardNumber, expiryDate, cvv, timeStamp]
db.run(sql, params, function (err, result) {
if (err) {
res.status(400).json({ "error": err.message })
return;
} else {
res.json({
"message": "success",
"data": req.body,
"id": this.lastID
})
}
});
} catch (E) {
res.status(400).send(E);
}
});
JavaScript:
const { text } = require('body-parser');
const { getEventListeners } = require('stream');
var sqlite3 = require('sqlite3').verbose();
const DBSOURCE = 'db.sqlite';
let db = new sqlite3.Database(DBSOURCE,(err) => {
if(err){
console.error(err.message)
throw err
}else{
console.log(`Connected to the SQlite Data base')
db.run( 'CREATE TABLE customer (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name text,
address text,
email text,
dateOfBirth text,
gender text,
age INTEGER,
cardHolderName text,
cardNumber INTEGER,
expiryDate text,
cvv INTEGER,
timeStamp text
)`, (err) => {
if (err){
// table already created
} else {
var insert = 'INSERT INTO customer' (name, address, email, dateOfBirth, gender, age, cardHolderName, cardNumber, expiryDate, cvv, timeStamp)
db.run(insert,["anura ariyaratne", "no 3, Panadura", "[email protected]", "1990.02.04", "male", 55, "Anura Ariyartne", 12456789056, 12/2022, 562, "2022.12.31.23.59.59"])
}
}
)
}
});
module.exports = db;