Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Postman error or code syntax

anuraa

Legendary Coder
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.

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;
 

Attachments

  • postman.png
    postman.png
    236.5 KB · Views: 2
  • VBscreen.png
    VBscreen.png
    136.5 KB · Views: 2
The error message is quite clear, is it not ? It looks from the second screenshot that you've been trying to create this table customer, but that hasn't worked. Looks like somehow you typed the closing quote and parenthesis in the wrong place, leaving the system all confused and sitting there waiting for more input. See image.
 

Attachments

  • a.jpg
    a.jpg
    17.4 KB · Views: 3
Thanks for the prompt reply with explanation as well. I find it hard to understand this syntax. Getting better acquainted little by little.

I put a terminator as follows, after trying to move the closing parenthesis to the end which resulted in VB giving error messages.

console.log(`Connected to the SQlite Data base');

The results were same. Could you please correct this syntax. Then, I will try to understand. Thanks again.
 
Aha, I had not really looked at your JS code. Now I see what's happening. Actually, the syntax highlighting should have alerted you too ! Look closely at what you did there.
The problem is that you are mixing single quotes and back quotes (backticks) for no good reason. In JS you can use single quotes, double quotes, or back quotes (the latter if you want variable substitution inside a string). All are valid but for heavens sake DO NOT MIX THEM !. Do not start a string with a backtick and then try to terminate it with a normal quote. You see the result: your create table command, instead of being executed, becomes part of the string you feed to console.log(). In this case there is absolutely no need for using backticks, so use normal quotes. I recommend using double quotes by default because a single quote and backtick look so similar. So try this

JavaScript:
console.log("Connected to the SQlite Data base")
db.run( "CREATE TABLE customer (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name text,
...
timeStamp text
)", (err) => {
...

I'm not sure all your parentheses and curly brackets are matching, but your indentation is so terrible that I will not even try to check 🙄
 
I am leaning. Following was the one, that I was following.
GitHub - opencourse5tutor/products-api: A service to manage product API s
If you look at the code carefully, specially following. You will see that after db.run('. It is an apostrophe character.
db.run(`CREATE TABLE customer

After much struggle, I managed to run the post API in POTMAN to see the words "success" there.

Thanks for the input. Thought of updating as it will help someone.
 

Attachments

  • VBScreen.png
    VBScreen.png
    131 KB · Views: 3
Solution
Yes, that starting backtick (or apostrophe, as you call it) was ruining it for you. Just remember to be careful with choosing and using your quote characters.
 
Thanks for correcting. Hope, you can help and guide me in the correct direction. Going forward, I included a validation to credit card number and Email, as shown below. I just guessed and POSTMAN didn't give any message. I looked for a a site to see the proper format. (type="email", cardNumber INTEGER LENGTH 12,). My free version of POSTMAN may not check. That is a one reason to ask your expert knowledge to check.


Code:
console.log('Connected to the SQlite database.')
        db.run(`CREATE TABLE customer (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name text,
            address text,
            email text type="email",
            dateOfBirth text,
            gender text,
            age INTEGER,
            cardHolderName text,
            cardNumber INTEGER LENGTH 12,
            expiryDate text,
            cvv INTEGER,
            timeStamp text
 
I don't know where you got that syntax from, but it's wrong. If you write SQL or DML for the server side, I strongly recommend that you first test that code in the database's own workbench. And why are you still using a backtick in the db.run command ?

Code:
C:\Users\Chris>C:\Sqlite\sqlite3.exe
SQLite version 3.39.3 2022-09-05 11:02:23
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> CREATE TABLE customer (
   ...>             id INTEGER PRIMARY KEY AUTOINCREMENT,
   ...>             name text,
   ...>             address text,
   ...>             email text type="email",
   ...>             dateOfBirth text,
   ...>             gender text,
   ...>             age INTEGER,
   ...>             cardHolderName text,
   ...>             cardNumber INTEGER LENGTH 12,
   ...>             expiryDate text,
   ...>             cvv INTEGER,
   ...>             timeStamp text)
   ...> ;
Parse error: near "=": syntax error
           address text,             email text type="email",             dateOf
                                      error here ---^
sqlite>        CREATE TABLE customer (
   ...>             id INTEGER PRIMARY KEY AUTOINCREMENT,
   ...>             name text,
   ...>             address text,
   ...>             email text,
   ...>             dateOfBirth text,
   ...>             gender text,
   ...>             age INTEGER,
   ...>             cardHolderName text,
   ...>             cardNumber INTEGER LENGTH 12,
   ...>             expiryDate text,
   ...>             cvv INTEGER,
   ...>             timeStamp text);
Parse error: near "12": syntax error
  rName text,             cardNumber INTEGER LENGTH 12,             expiryDate t
                                      error here ---^
 
Yes, I am in db.run. What do you suggest. I want to expand on this first and then, to learn SQL. I am looking for a source for the proper syntax. Still no luck. Thanks
 
Sure, I can see you are in db.run. What I suggested is you take that command to SQLite on your client and execute it. Just install SQLite local, run sqlite3.exe, paste the command and you will see that it has two errors. I don't know where you got that syntax from but I don't think you can define constraints like this. Please study this tutorial which will help you.
 
Would you please look at your error handling code and ask yourself why you are not seeing any errors ? If you don't pay attention to your code, and also do not follow my suggestions, I will not help you any longer.
 
I love your help. Following was a one that you helped me to understand. Still, I am at the very beginner stage to expand. It is a big struggle here. I expected the POSTMAN to throw errors.


Code:
<script>
  var sidenav = document.getElementById("sidenav");
    
  menu.onclick = function(event){
  openNav();
  event.stopPropagation();
  }

  function openNav() {
    document.getElementById("sidenav").style.width = "30%";
  }
  function closeNav() {
    document.getElementById("sidenav").style.width = "0";
  }
  window.onclick = function(event) {
    if ( sidenav.style.width != 0 && event.target != sidenav )  {
    closeNav();
    }
  }
</script>
one that you helped me to understand.
 
I understand you are a beginner, and that is fine. But the least you could do is follow my suggestions, which once again you are ignoring ! This is getting really tiring now.
One more try then. Look at your code here and tell me why you expect postman to return you an error ? That is the one thing it will never do 🙄

a.jpg
 
Thanks
I changed as follows.
Code:
let db = new sqlite3.Database(DBSOURCE, (err) => {
    if (err) {
        // Cannot open database
        console.error(err.message)
        throw err
    } else {
        console.log('Connected to the SQlite database.')
        db.run(`CREATE TABLE customer (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name text,
            address text,
            email text type="EMAIL",
            dateOfBirth text,
            gender text,
            age INTEGER,
            cardHolderName text,
            cardNumber INTEGER LENGTH 12,
            expiryDate text,
            cvv INTEGER,
            timeStamp text
            )`, (err) => {
                console.log("Data type Error");
            if (err) {
                // Table already created
            } else {
                // Table just created, creating some rows
                var insert = 'INSERT INTO customer (name, address, email, dateOfBirth, gender, age, cardHolderName, cardNumber, expiryDate, cvv, timeStamp) VALUES (?,?,?,?,?,?,?,?,?,?,?)'
                db.run(insert, ["anura ariyaratne", "no 3, Panadura", "[email protected]", "1990.02.04", "male", 55, "Anura Ariyartne", 123456789056, 12/2022, 562, "2022.12.31.23.59.59"])
            }
        })
    }
})

module.exports = db;

Console Message
---------------

PS C:\Users\aariy\guidedPrj> node database.js
Connected to the SQlite database.
Data type Error
PS C:\Users\aariy\guidedPrj> node server.js
Server is running on 8071
Connected to the SQlite database.
Data type Error

Then, I removed the "type="EMAIL", and LENGTH 12.
Saw the same message on the VB Terminal. POSTMAN created the data. Thanks
 
Well at least you are one step further. The error handling still sucks though.… now you always give the message "Data type Error". I would do that only if there actually was an error 😁 And then print the err object itself, instead of assuming it was a data type error - like previously you assumed any error would mean "table already exists". If the err object does not have a detailed error text, there most likely there is an SQLite function that gives you one. There are three golden rules about error handling:
  • Do not assume anything
  • Print as much detail information as you can get
  • Do it properly or don't bother at all
I hope that makes sense.
 
How about this. Still, running node database.js gives me the terminal same
var sqlite3 = require('sqlite3').verbose()
var md5 = require('md5')
const DBSOURCE = "db.sqlite"

JavaScript:
var sqlite3 = require('sqlite3').verbose()
var md5 = require('md5')

const DBSOURCE = "db.sqlite"


let db = new sqlite3.Database(DBSOURCE, (err) => {
    if (err) {
        // Cannot open database
        console.error(err.message)
        throw err
    } else {
        console.log('Connected to the SQlite database.')
        db.run(`CREATE TABLE customer (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name text,
            address text,
            email text type="EMAIL",
            dateOfBirth text,
            gender text,
            age INTEGER,
            cardHolderName text,
            cardNumber INTEGER LENGTH 12,
            expiryDate text,
            cvv INTEGER,
            timeStamp text
            )`, (err) => {
                if (err) {
                console.log("Data type Error");
                }
            if (err) {
                // Table already created
            } else {
                // Table just created, creating some rows
                var insert = 'INSERT INTO customer (name, address, email, dateOfBirth, gender, age, cardHolderName, cardNumber, expiryDate, cvv, timeStamp) VALUES (?,?,?,?,?,?,?,?,?,?,?)'
                db.run(insert, ["anura ariyaratne", "no 3, Panadura", "[email protected]", "1990.02.04", "male", 55, "Anura Ariyartne", 123456789056, 12/2022, 562, "2022.12.31.23.59.59"])
            }
        })
    }
})

module.exports = db;
 
I changed as follows to see errors on VB Terminal.

PS C:\Users\aariy\guidedPrj> node database.js
Connected to the SQlite database.
SQLITE_ERROR: table customer already exists
undefined:0


Error: SQLITE_ERROR: table customer already exists
--> in Database#run('CREATE TABLE customer (\n' +
' id INTEGER PRIMARY KEY AUTOINCREMENT,\n' +
' name text,\n' +
' address text,\n' +
' email text type="EMAIL",\n' +
' dateOfBirth text,\n' +
' gender text,\n' +
' age INTEGER,\n' +
' cardHolderName text,\n' +
' cardNumber INTEGER LENGTH 12,\n' +
' expiryDate text,\n' +
' cvv INTEGER,\n' +
' timeStamp text\n' +
' )', [Function (anonymous)])
at Database.<anonymous> (C:\Users\aariy\guidedPrj\database.js:14:12) {
errno: 1,
code: 'SQLITE_ERROR',
__augmented: true
}

Node.js v18.16.0


Code:
var sqlite3 = require('sqlite3').verbose()
var md5 = require('md5')

const DBSOURCE = "db.sqlite"


let db = new sqlite3.Database(DBSOURCE, (err) => {
    if (err) {
        // Cannot open database
        console.error(err.message)
        throw err
    } else {
        console.log('Connected to the SQlite database.')
        db.run(`CREATE TABLE customer (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name text,
            address text,
            email text type="EMAIL",
            dateOfBirth text,
            gender text,
            age INTEGER,
            cardHolderName text,
            cardNumber INTEGER LENGTH 12,
            expiryDate text,
            cvv INTEGER,
            timeStamp text
            )`, (err) => {
                if (err) {
                    console.error(err.message);
                    throw err
                }
            if (err) {
                // Table already created
            } else {
                // Table just created, creating some rows
                var insert = 'INSERT INTO customer (name, address, email, dateOfBirth, gender, age, cardHolderName, cardNumber, expiryDate, cvv, timeStamp) VALUES (?,?,?,?,?,?,?,?,?,?,?)'
                db.run(insert, ["anura ariyaratne", "no 3, Panadura", "[email protected]", "1990.02.04", "male", 55, "Anura Ariyartne", 123456789056, 12/2022, 562, "2022.12.31.23.59.59"])
            }
        })
    }
})

module.exports = db;
 
I don’t want to give up on this project with db.run. Unless, a person like you help me, it is difficult to understand. This is few tiring days to grasp the flow of logic, syntax right.
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom