I get a Cannot POST /login error when i’m not sending a POST request to the /login endpoint

  Kiến thức lập trình

I’m building a web application where users can register and login using Node.js, Express, and a PostgreSQL database. However, I’m encountering an issue with my frontend and backend communication. When I attempt to submit the login or register form, the web page only shows the text Cannot POST /login (for both pages)

I was expecting it to add the name, username, and password to the database, the steps ive taken are:

Backend Configuration:

I’ve defined the necessary POST routes (/login-user and /register-user) in my Express server (server.js).
The routes handle POST requests to validate user credentials or register new users in the database using knex.
Frontend Implementation:

I have implemented a form validation and submission logic using JavaScript’s fetch API.
Depending on whether the form is for login or registration (name == null), the frontend sends a POST request to /login-user or /register-user endpoints.

BACK END

var http = require('http');
const express = require('express')
const path = require('path');
const bodyParser = require('body-parser');
const knex = require('knex');

const db = knex({
  client: 'pg',
  connection: {
      host: '127.0.0.1',
      user: 'postgres',
      password: 'Alexander1!',
      database: 'loginform'
  }
})

const app = express();

const initialPath = path.join(__dirname, "");

app.use(bodyParser.json());
app.use(express.static(initialPath));



app.get('/', (req, res) => {
    res.sendFile(path.join(initialPath, "index.html"));
})

app.get('/login', (req, res) => {
    res.sendFile(path.join(initialPath, "loginpage.html"));
})

app.get('/register', (req, res) => {
    res.sendFile(path.join(initialPath, "signuppage.html"));
})

app.post('/register-user', (req, res) => {
    const { name, username, password } = req.body;

    if(!name.length || !username.length || !password.length){
        res.json('fill all the fields');
    } else{
        db("users").insert({
            name: name,
            username: username,
            password: password
        })
        .returning(["name", "username"])
        .then(data => {
            res.json(data[0])
        })
        .catch(err => {
            if(err.detail.includes('already exists')){
                res.json('username already exists');
            }
        })
    }
})

app.post('/login-user', (req, res) => {
    const { username, password } = req.body;

    db.select('name', 'username')
    .from('users')
    .where({
        username: username,
        password: password
    })
    .then(data => {
        if(data.length){
            res.json(data[0]);
        } else{
            res.json('username or password is incorrect');
        }
    })
})

app.listen(3000, (req, res) => {
    console.log('listening on port 3000......')
})

FRONT END

// form loading animation

const form = [...document.querySelector('.form').children];

form.forEach((item, i) => {
    setTimeout(() => {
        item.style.opacity = 1;
    }, i*100);
})

window.onload = () => {
    if(sessionStorage.name){
        location.href = '/';
    }
}

// form validation

const name = document.querySelector('.name') || null;
const username = document.querySelector('.username');
const password = document.querySelector('.password');
const submitBtn = document.querySelector('.submit-btn');

if(name == null){ // means login page is open
    submitBtn.addEventListener('click', () => {
        fetch('/login-user',{
            method: 'post',
            headers: new Headers({'Content-Type': 'application/json'}),
            body: JSON.stringify({
                username: username.value,
                password: password.value
            })
        })
        .then(res => res.json())
        .then(data => {
            validateData(data);
        })
    })
} else{ // means register page is open

    submitBtn.addEventListener('click', () => {
        fetch('/register-user', {
            method: 'post',
            headers: new Headers({'Content-Type': 'application/json'}),
            body: JSON.stringify({
                name: name.value,
                username: username.value,
                password: password.value
            })
        })
        .then(res => res.json())
        .then(data => {
            validateData(data);
        })
    })

}

const validateData = (data) => {
    if(!data.name){
        alertBox(data);
    } else{
        sessionStorage.name = data.name;
        sessionStorage.username = data.username;
        location.href = '/';
    }
}

const alertBox = (data) => {
    const alertContainer = document.querySelector('.alert-box');
    const alertMsg = document.querySelector('.alert');
    alertMsg.innerHTML = data;

    alertContainer.style.top = `5%`;
    setTimeout(() => {
        alertContainer.style.top = null;
    }, 5000);
}

New contributor

rbt is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT