PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 20, 2022

[FIXED] How can I fix this Node.js login page?

 October 20, 2022     express, html, javascript, node.js     No comments   

Issue

I'm breaking my head with a Node js with mysql database and trying to make a simple login.

I am getting :Cannot POST /login

<body class="hero-image">

<div id="container">
    <div id="tabs">

       <p id="lt" class="tabs">Log in</p>
        <p id="rt" class="tabs" onclick="location.href = './register';">Register</p>

        <div id="clear"></div>
    </div>
    <div id="cont">
        <div id="loginBox" class="comm">
            <h3>Sign in</h3>
            <form action="login" method="POST">
                <input id="username" type="text" autocomplete="off" name="username" placeholder="Username" required>
                <input id="password" type="password" autocomplete="off" name="password" placeholder="Password" required>
                <input type="submit" value="Submit Form">
            </form>
        </div>
    </div>
</div>
<script>
        const form = document.getElementById('login')
        form.addEventListener('submit', login)

        async function login(event) {
            alert('Success')
            event.preventDefault()
            const username = document.getElementById('username').value
            const password = document.getElementById('password').value
            
            
            
            const result = await fetch('/api/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username,
                    password
                })
            }).then((res) => res.json())

            if (result.status === 'ok') {
                // everythign went fine
                console.log('Got the token: ', result.data)
                localStorage.setItem('token', result.data)
                alert('Success')
            } else {
                if (result.status === 'Not Found') {
                    alert("Incorrect Username and/or Password!");
                }
                else {
                    alert("Please enter Username and Password!");
                }
            }
        }
    </script>
And this node js script: ``` var mysql = require('mysql'); var express = require('express'); var session = require('express-session'); var bodyParser = require('body-parser'); var path = require('path') const jwt = require('jsonwebtoken') var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : 'sportacus3', database : 'nodelogin' }); var app = express(); app.use(session({ secret: 'secret', resave: true, saveUninitialized: true })); app.get("/login", (req, res) => { res.sendFile(__dirname + "/login.html"); }); app.get("/", (req, res) => { res.sendFile(__dirname + "/landing-page.html"); }); app.get("/register", (req, res) => { res.sendFile(__dirname + "/register.html"); }); app.use(bodyParser.urlencoded({extended : true})); app.use(bodyParser.json()); app.get('/', function(request, response) { response.sendFile(path.join(__dirname + '/login.html')); }); app.post('/api/login', async (req, res) => { var dialog = require('dialog'); const { username, password } = req.body; if (!username) { return res.json({ status: 'Not Found', data: 'Invalid username/password' }); } if (username && password) { connection.query('SELECT * FROM users WHERE username = ? AND password = ?', [username, password], function(error, results, fields) { if (results.length > 0) { return res.json({ status: 'ok', data: username }); } else { return res.json({ status: 'Not Found', data: 'Incorrect Username and/or Password!' }); } }); } }); app.get('/home', function(request, response) { if (request.session.loggedin) { response.send('Welcome back, ' + request.session.username + '!'); response.end(); } else { //response.send('Please login to view this page!'); alert('Please login to view this page!'); } }); app.listen(3000); ``` I'd really appreciate the help!

Solution

Well, bro!

I tried to make an effort to unscramble the backend code but for now you're posting to the "/api/login" and your html form action is targeting "login".

To make the right call to the post method, change your html to the following action:

 <form action="/api/login" method="POST">

So it matches the right call you're trying to do, which is:

app.post("/api/login", async(req, res) => {...});


Answered By - Rafael Nicola
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing