1.
npm init -y
[Link] install express mysql body-parser
[Link] database
CREATE DATABASE nodejsdb;
USE nodejsdb;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
4. create public folder and paste the code
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert User Data</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 50px;
}
form {
max-width: 400px;
margin: 0 auto;
}
label, input {
display: block;
margin-bottom: 10px;
}
button {
padding: 10px 20px;
background-color: #007BFF;
color: white;
border: none;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Insert User Data</h1>
<form action="/adduser" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>
</body>
</html>
5. create [Link] file
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
// Middleware to parse form data
[Link]([Link]({ extended: true }));
// Serve the HTML form
[Link]([Link]([Link](__dirname, 'public')));
// Create MySQL connection
const db = [Link]({
host: 'localhost',
user: 'root',
password: '', // Your XAMPP MySQL root password
database: 'nodejsdb'
});
// Connect to MySQL
[Link]((err) => {
if (err) {
throw err;
}
[Link]('MySQL Connected...');
});
// Insert data route
[Link]('/adduser', (req, res) => {
const user = { name: [Link], email: [Link] };
const sql = 'INSERT INTO users SET ?';
[Link](sql, user, (err, result) => {
if (err) {
[Link]('Error inserting data:', [Link]);
[Link]('There was an error inserting the data.');
} else {
[Link]('User added successfully!');
}
});
});
// Start the server
const PORT = [Link] || 3000;
[Link](PORT, () => {
[Link](`Server started on port ${PORT}`);
});
[Link] server
node [Link]
7. port address
localhost:3000