Home > Net >  Node JS User Validation using Data Base
Node JS User Validation using Data Base

Time:02-04

I'm trying to perform user validation with a data base. Whenever I try to enter in the credentials on the form, the page will load "http://localhost:3000/users" with the message

Cannot POST /users

I'm fairly certain my code is correct? I'm not sure what I have done wrong any help would be very appreciated. My code is below

var express = require('express');
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(':memory:');
var app = express();


app.use(express.static('public_html'));

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port)

function normalizePort(val) {
var port = parseInt(val , 10);
if(isNaN(port)) {

return val;
}
if (port >= 0) {

return port;
} return false;
}
app.use(express.urlencoded({ extended: false }));

db.serialize(function () {

    db.run("CREATE TABLE IF NOT EXISTS USER (id INTEGER NOT NULL PRIMARY KEY, username TEXT UNIQUE, password TEXT, fullname TEXT, purchase INTEGER, delivered INTEGER, vouchers INTEGER)");
    
    db.run('INSERT INTO User (username, password, fullname, purchase, delivered, vouchers) VALUES ("george23", "night104", "George Smith", 3, 14, 2)');
    db.run('INSERT INTO User (username, password, fullname, purchase, delivered, vouchers) VALUES ("worldtime", "super34", "John Lennon", 0, 43, 8)');
    db.run('INSERT INTO User (username, password, fullname, purchase, delivered, vouchers) VALUES ("funtime82", "everyday1", "Ringo Starr", 3, 2, 1)');
    db.run('INSERT INTO User (username, password, fullname, purchase, delivered, vouchers) VALUES ("treeman28", "plants4", "Elon Musk", 89, 39, 29)');
    db.run('INSERT INTO User (username, password, fullname, purchase, delivered, vouchers) VALUES ("amazon1", "amazon4ever", "Jeff Bezos", 38, 0, 1)');
    
    console.log('Displaying all the content from every row of the DB');
    db.each("SELECT * FROM User", function (err, row) {
        console.log("[all] User Name: "   row.username   " Password: "   row.password   " Full Name: "   row.fullname   row.purchase   row.delivered   row.vouchers);
    
         });
    });

app.get('/users', function (req, res, next) {
    let html = '';
    let username = req.query.username;
    let password = req.query.password;
    let totalPurchase = 0;

    console.log("Just received GET data for users endpoint.");
    console.log(`Data includes: ${username}, ${password}`);
    console.log(username   password);

    html  = '<!doctype html><html lang="en">';
    html  = '<head>';
    html  = '<title>Online Store</title>';
    html  = '<meta charset="utf-8">';
    html  = '<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">';
    html  = '<link rel="stylesheet"';
    html  = '  href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"';
    html  = '  integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP VmmDGMN5t9UJ0Z"';
    html  = '  crossorigin="anonymous">';
    html  = '</head>';

    html  = '<body><div >';

    db.all(`SELECT * FROM User WHERE username = "${username}" AND password = "${password}"`, function (err, row) {
    if (err) {
        return console.error(err.message);
    }
        
    if (row.length === 0) {
        console.log("Unknown user!");
        html  = '<h1>Login Failed</h1>';
        html  = 'the <em>User Name</em> or <em>Password</em> provide does not match or does not exist';
    } else {
        
        totalPurchase = row[0].purchase   row[0].delivered;
        console.log("Known user!");
        html  = '<h1>Login Success</h1>';
        html  = '<p>Thank you <strong>'   row[0].username   "</strong> (username '"   row[0].fullname   "'). Login Success </p>";
        html  = '<p>Our records show you have purchased a total of <strong>'   totalPurchase   "</strong> dog food items <strong>Dog Food Store</strong>.</p>";

            html  = '<p>Your purchase records are:</p>';
            html  = '<ul><li> Instore = '   row[0].purchase   '</li>';
            html  = '<li> Delivered = '   row[0].delivered   '</li>';
            html  = '<li> Vouchers = '   row[0].vouchers   '</li></ul>';

        };
        html  = '</div>';
        html  = '</body></html>';
        res.send(html);

    });

});


app.listen(port, function () 
{
    console.log("Web server running at: http://localhost:3000");
    console.log("Type Ctrl c to shut down the server");
});

I've also included my index.html file.

<!doctype html>
<html lang="en">

<head>
    <title>Pet Store DataBase Form</title>

    <meta charset="utf-8">
    <meta name="Pet Store Writer" content="Pet Store">
    <meta name="description" content="Pet Store">
    <meta name="viewport"
        content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Latest compiled and minified CSS -->
    <!-- CSS only -->
    <link rel="stylesheet"
        href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
        integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP VmmDGMN5t9UJ0Z"
        crossorigin="anonymous">
</head>

<body>
    <div >

        <h1>Pet Store</h1>
        <br>
        <h2>Customer Login:</h2>

        <form action="/users" method="post">
            <div >
                <label for="username">User Name:</label>
                <input type="text"  name="username" id="username">
            </div>
            <div >
                <label for="password">Password:</label>
                <input type="password"  name="password" id="password">
            </div>
            
        
            <button type="submit" value="Login"
                >Submit</button>     
            
        </form>

    </div>

    <!-- jQuery library -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C OGpamoFVy38MVBnE IbbVYUew OrCXaRkfj"
        crossorigin="anonymous"></script>
    <script
        src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
        integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU 6BZp6G7niu735Sk7lN"
        crossorigin="anonymous"></script>
    <script
        src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
        integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV rV"
        crossorigin="anonymous"></script>
</body>
</html>

CodePudding user response:

your code may be correct but not complete.

You are trying to send data to a path on your server.

You called this route "/users"

When you do this, you use a HTTP verb. The verb you are using in this regard is the POST verb.

The server does not find any handler to handle the post verb at that particular route.

It responds back with : "Cannot POST /users"

The solution to this is for you to declare an handler to handle post request to the users route.

Add this line of code after the end of app.get("/users" , function(req , res , next){ //Removed for brevity sake })

See the code to add below :

    app.post("/users" , (req , res) => {
        //Add your own implementation here
        res.send("Not yet implemented")
    })

CodePudding user response:

Check the express documentation https://expressjs.com/en/starter/basic-routing.html

app.route('/users')
  .get(function(req, res) {
    res.send('Get an user');
  })
  .post(function(req, res) {
    res.send('Add an user');
  })
  .put(function(req, res) {
    res.send('Update an user');
  });

You don't have post method

  •  Tags:  
  • Related