skip to Main Content

I wanted the user to enter his credentials and be redirected to another html page if it matches the one in the database. If it doesn’t give an error message. I tried so many methods but I couldn’t seem to get it. I will leave the files here. yall do your thing please.
Here is the html page that accepts user credentials.

`<body>
    <form action="login" method="post" class="form">
        <h4>authenticate</h4>
        <hr class="under-line">
        <div class="form-row">
            <label for="username" class="form-label">UserName</label>
            <input type="text" 
            id="username"
            name="username"
            required
            class="form-input">
        </div>
        <div class="form-row">
            <label for="password" class="form-label">Password</label>
            <input type="password" 
            id="password"
            name="password"
            required
            class="form-input">
        </div>
        <button id="submitButton" type="submit" class="btn btn-block btn-teritiary">Submit</button>
    </form>
    

</body>`

here is the env file

DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=5321
DB_NAME=HRdatabase

and here is the app.js that handles the backend

`require('dotenv').config();

const { Pool } = require('pg');

const pool = new Pool({
    host: process.env.DB_HOST,
    port: process.env.DB_PORT,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME
});

pool.on('error', (err) => {
    console.error('Error connecting to PostgreSQL:', err);
    process.exit(1);
});


express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 5500; // Use a default port if not specified

app.use(bodyParser.urlencoded({ extended: false }));

// Route for hrauthentication.html (assuming it's in the project's root)
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/HRauthentication.html');
});

// Route to handle login form submission (POST request)
app.post('/login', async (req, res) => {
    const { username, password } = req.body;

    try {
        const client = await pool.connect();
        const result = await client.query('SELECT * FROM hrmanagers WHERE username = $1', );

        if (result.rows.length === 0) {
            // Username not found
            return res.status(401).send('Invalid username or password');
        }

        const user = result.rows[0];
        if (password !== user.password) {
            // Incorrect password
            return res.status(401).send('Invalid username or password');
        }

        // Successful login, redirect to hrpage.html
        res.redirect('/HRpage'); // Assuming hrpage.html is in the project's root
    } catch (err) {
        console.error('Error during login:', err);
        res.status(500).send('Internal Server Error');
    } finally {
        pool.release(client);
    }
});

// Route for hrpage.html (assuming it's in the project's root)
app.get('/hrpage', (req, res) => {
    res.sendFile(__dirname + '/hrpage.html');
});

app.listen(port, () => {
    console.log(`Server listening on port ${port}`);
  });`

I have downloaded every dependency needed and start node js. I also created a database in pgadmin. I connected everything. I expected it to authenticate the user and take him to another page called "hrpage.html" but it didn’t. when i click submit it takes me to a page saying "This page isn’t working. HTTP ERROR 405. I need help ASAP.

2

Answers


  1. In Login API’s finally block, you are trying to access release() method on pool, but pool does not provide any method named release. Instead you can use client.release() to remove the connection.

    You can use below updated code for login API

    app.post('/login', async (req, res) => {
        let client;
        const { username, password } = req.body;
    
        try {
            client = await pool.connect();
            const result = await client.query('SELECT * FROM hrmanagers WHERE username = $1', [username]);
    
            if (result.rows.length === 0) {
                // Username not found
                return res.status(401).send('Invalid username or password');
            }
    
            const user = result.rows[0];
            if (password !== user.password) {
                // Incorrect password
                return res.status(401).send('Invalid username or password');
            }
    
            // Successful login, redirect to hrpage.html
            res.redirect('/HRpage'); // Assuming hrpage.html is in the project's root
        } catch (err) {
            console.error('Error during login:', err);
            res.status(500).send('Internal Server Error');
        } finally {
            client.release();
        }
    });
    

    Hope this helps!

    Login or Signup to reply.
  2. I handled the redirect thing on the client side script, Hope this helps !

    https://github.com/vihanpereraux/stackoverflow-fixes/tree/main/auth-redirect-path-fix

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search