0% found this document useful (0 votes)
17 views

Nodejs

node js basic

Uploaded by

jebinp08
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Nodejs

node js basic

Uploaded by

jebinp08
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

1.

npm init -y
2.npm install express mysql body-parser
3.create 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

index.html

<!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 app.js 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


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

// Serve the HTML form


app.use(express.static(path.join(__dirname, 'public')));

// Create MySQL connection


const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '', // Your XAMPP MySQL root password
database: 'nodejsdb'
});

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

// Insert data route


app.post('/adduser', (req, res) => {
const user = { name: req.body.name, email: req.body.email };
const sql = 'INSERT INTO users SET ?';
db.query(sql, user, (err, result) => {
if (err) {
console.error('Error inserting data:', err.message);
res.send('There was an error inserting the data.');
} else {
res.send('User added successfully!');
}
});
});

// Start the server


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

6.start server

node app.js
7. port address

localhost:3000

You might also like