Home > OS >  Cannot POST /login error - while clicking submit using Node.js and Express.js with MySql
Cannot POST /login error - while clicking submit using Node.js and Express.js with MySql

Time:02-01

I am trying to build simple login page using node.js with express.js package and mysql package, that will redirect the user to layout.html page, if the username and password exists in mysql database.

I run mysql on my localhost, and I've created a database with tables and users in mysql workbench.

The node.js server is also being run on localhost using liteserver.

After I am clicking on "Submit" button on my page, no matter if there is any data written into (username) and (password) boxes, I am getting an Error saying "Cannot POST /login"

That is all the code I have, all my javascript code is in one file.

**script.js **


import express from 'express';
const app = express();
import { createConnection } from 'mysql';
import bodyParser from 'body-parser';

const router = express.Router();

// Create a connection to the MySQL server
const connection = createConnection({
  host: 'localhost', // The hostname of the MySQL server
  user: 'pablo', // The username to connect to the server
  password: 'KotWButach!', // The password for the usernam
  database: 'logowanie' // The name of the database
});

// Connect to the MySQL server
connection.connect();

connection.connect((err) => {
  if (err) {
    console.error(`Error connecting to the database: ${err.stack}`);
    return;
  }
  console.log(`Connected to the database with id: ${connection.threadId}`);
});

connection.query(query, (error, results) => {
  if (error) {
    console.error(`Error executing the query: ${error.stack}`);
    return res.status(500).send({ error });
  }
});



// Parse the request body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

router.post('/login');

app.post('/login', (req, res) => {
  const { username, password } = req.body; // Destructure the username and password from the request body

  // Query the users table to check if the provided username and password match a record in the table
  const query = `SELECT * FROM users WHERE UserName = '${username}' AND UserPass = '${password}'`;
  connection.query(query, (error, results) => {
    if (error) {
      return res.status(500).send({ error });
    }
    if (results.length === 0) {
      return res.status(401).send({ message: 'Invalid username or password' });
    }
    // If the username and password match a record in the table, redirect to the layout.html page
    res.redirect('/layout.html');
  });
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

index.html

<!DOCTYPE html>
<html>
  <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'nonce-randomvalue'">
<head>
  <link rel="stylesheet" type="text/css" href="styles.css">
  <title>Login</title>
  <script nonce="randomvalue" src="script.js"></script>
</head>
<body>
  <form action="/login" method="post">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username">
    <br>
    <label for="password">Password:</label>
    <input type="password" id="password" name="password">
    <br><br>
    <input type="submit" value="Submit">
  </form> 
</body>
</html>

I am expecting it to be able to redirect to layout.html after clicking submit (with credentials that match with the ones in the database), or get an error saying "invalid username or password" it they aren't matching.

I've scrolled through more than 30 cases on stackoverflow and none of the answers seem to work or me, I've even asked ai for what to do but it got stuck on the loop telling me to check if my routing is correct.

CodePudding user response:

You could simply remove theses lines in your code that cause the error that you have :

Remove just this line :

router.post('/login');

You declare a api endpoint which has no callback behind and point to "/login", that's why you have the error.

After remove it, you can also remove the router you declare previously as you won't need it anymore.

CodePudding user response:

Would you share the full code? Or please refer this code.

import express from 'express';
const app = express();
import { createConnection } from 'mysql';
import bodyParser from 'body-parser';
import { dirname } from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const router = express.Router();

// Create a connection to the MySQL server
const connection = createConnection({
  host: 'localhost', // The hostname of the MySQL server
  user: 'pablo', // The username to connect to the server
  password: 'KotWButach!', // The password for the usernam
  database: 'logowanie' // The name of the database
});

// Connect to the MySQL server
connection.connect();

connection.connect((err) => {
  if (err) {
    console.error(`Error connecting to the database: ${err.stack}`);
    return;
  }
  console.log(`Connected to the database with id: ${connection.threadId}`);
});

// connection.query(query, (error, results) => {
//   if (error) {
//     console.error(`Error executing the query: ${error.stack}`);
//     return res.status(500).send({ error });
//   }
// });



// Parse the request body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/', router);

app.get('/', (req, res) => {
    res.sendFile(__dirname   '/index.html');
});

app.get('/layout', (req, res) => {
    res.sendFile(__dirname   '/layout.html');
});

app.set('view engine', 'html')

router.post('/login');

app.post('/login', (req, res) => {
  const { username, password } = req.body; // Destructure the username and password from the request body

  // Query the users table to check if the provided username and password match a record in the table
  const query = `SELECT * FROM users WHERE UserName = '${username}' AND UserPass = '${password}'`;
  connection.query(query, (error, results) => {
    if (error) {
      return res.status(500).send({ error });
    }
    if (results.length === 0) {
      return res.status(401).send({ message: 'Invalid username or password' });
    }
    // If the username and password match a record in the table, redirect to the layout.html page
    res.redirect('/layout');
  });
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});
  • Related