ขั้นตอนการติดตั้ง
ก่อนสร้างฟอร์มสมัครสมาชิก ต้องติดตั้ง dependencies ต่อไปนี้:
Express - ใช้ตั้งค่า middleware ตอบสนอง HTTP requests
npm install express --save
body-parser - อ่านข้อมูล HTTP POST
npm install body-parser --save
Mongoose - ODM สำหรับ MongoDB บน Node.js
npm install mongoose --save
โครงสร้างไฟล์
app.js- ไฟล์หลักของเซิร์ฟเวอร์public/- โฟลเดอร์เก็บไฟล์ staticindex.html- หน้าฟอร์มสมัครsuccess.html- หน้าสำเร็จstyle.css- ไฟล์สไตล์
รันแอปพลิเคชัน
node app.js
โค้ดหลัก (app.js)
var express=require("express");
var bodyParser=require("body-parser");
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/tutorialsPoint');
var db=mongoose.connection;
db.on('error', console.log.bind(console, "connection error"));
db.once('open', function(callback){
console.log("connection succeeded");
})
var app=express()
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/sign_up', function(req,res){
var name = req.body.name;
var email =req.body.email;
var pass = req.body.password;
var phone =req.body.phone;
var data = {
"name": name,
"email":email,
"password":pass,
"phone":phone
}
db.collection('details').insertOne(data,function(err, collection){
if (err) throw err;
console.log("Record inserted Successfully");
});
return res.redirect('success.html');
})
app.get('/',function(req,res){
res.set({ 'Access-control-Allow-Origin': '*' });
return res.redirect('index.html');
}).listen(3000)
console.log("server listening at port 3000");
หน้า HTML และ CSS
ไฟล์ index.html มีฟอร์มกรอกชื่อ, อีเมล, รหัสผ่าน, เบอร์โทร พร้อม validation required
ไฟล์ success.html แสดงข้อความ "Signup Successful"
ไฟล์ style.css จัดรูปแบบฟอร์ม ให้ดูสวยงามทันสมัย
ผลลัพธ์
เปิดเบราว์เซอร์ที่ https://localhost:3000 จะเห็นหน้าฟอร์มสมัคร กรอกข้อมูลกด Submit จะบันทึกลง MongoDB และนำไปหน้าสำเร็จ
คอนโซลจะแสดง log การเชื่อมต่อและ "Record inserted Successfully"