Basic Login System with Node.js, Express, and MySQL

Creating a basic login system with Node.js, Express and MySQL allows for the use of JavaScript on both the front end and back end. While PHP is also commonly used for building login systems, using Node.js offers certain advantages such as a single language for both client-side and server-side development, asynchronous programming and scalability. Below, I’ll outline how to create a basic login system with Node.js, Express, and MySQL, and then I’ll provide a comparison with PHP.

Setup & File Structure

1. Requirements:
– Node.js and npm installed on your machine.
– MySQL database server.

2. File Structure:

  
project/
│
├── public/
│ └── css/
│ └── style.css
│
├── views/
│ └── login.html
│
├── app.js
└── package.json

 Creating the Login Template with HTML (views/login.html)

  <!-- views/login.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<h2>Login</h2>
<form action="/login" method="POST">
<div>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</div>
<button type="submit">Login</button>
</form>
</body>
</html>

Creating the Login App with Node.js (app.js)

  // app.js
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');

const app = express();

// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));

// MySQL Connection
const db = mysql.createConnection({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database'
});

// Connect to MySQL
db.connect((err) => {
if (err) {
throw err;
}
console.log('Connected to MySQL');
});

// Routes
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/login.html');
});

app.post('/login', (req, res) => {
const { username, password } = req.body;
const sql = `SELECT * FROM users WHERE username = ? AND password = ?`;
db.query(sql, [username, password], (err, result) => {
if (err) {
throw err;
}
if (result.length > 0) {
res.send('Login successful!');
} else {
res.send('Invalid username or password!');
}
});
});

// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

Explanation:

– This setup uses Express.js for handling HTTP requests, Body-Parser for parsing request bodies, and the MySQL package for interacting with the MySQL database.

– The login form is served using a static HTML file (`login.html`) located in the `views` directory.

– When the user submits the login form, the data is sent to the `/login` route using a POST request.

– In the `/login` route, the username and password are extracted from the request body, and a MySQL query is executed to check if the user exists in the database.

– If the user is found, a success message is sent back to the client; otherwise, an error message is sent.

Comparison with PHP:

While both PHP and Node.js can be used to create login systems, the choice between them depends on various factors:

1. Language Preference:

– PHP is a server-side scripting language specifically designed for web development.

– Node.js uses JavaScript, which is widely known and popular among developers for both front-end and back-end development.

2. Asynchronous Programming:

– Node.js is inherently asynchronous, making it suitable for handling multiple requests concurrently.

– PHP traditionally follows a synchronous model, although asynchronous frameworks like ReactPHP are available.

3. Scalability:

– Node.js is known for its ability to handle high concurrency and scale easily, making it suitable for real-time applications and microservices.

– PHP applications can also scale well with proper architecture and caching mechanisms.

4. Ecosystem:

– PHP has a mature ecosystem with widely used frameworks like Laravel, Symfony, and CodeIgniter.
– Node.js has a rapidly growing ecosystem with frameworks like Express.js, Nest.js, and Sails.js.

In summary, while PHP is a solid choice for building web applications, especially for those already familiar with the language, Node.js offers certain advantages such as a unified language stack and scalability, making it an attractive option for modern web development. Ultimately, the choice between PHP and Node.js depends on the specific requirements and preferences of the project and development team.

Add a Comment

Your email address will not be published. Required fields are marked *

ABOUT CODINGACE

My name is Nohman Habib and I am a web developer with over 10 years of experience, programming in Joomla, Wordpress, WHMCS, vTiger and Hybrid Apps. My plan to start codingace.com is to share my experience and expertise with others. Here my basic area of focus is to post tutorials primarily on Joomla development, HTML5, CSS3 and PHP.

Nohman Habib

CEO: codingace.com

Request a Quote









PHP Code Snippets Powered By : XYZScripts.com