使用 Nodejs 和 MongoDB 的注册表单
装置
首先,我们需要为我们的 Nodejs 应用程序包含一些包。
npm install express --save
Express 允许我们设置中间件来响应 HTTP 请求。
npm install body-parser --save
如果要读取 HTTP POST 数据,则必须使用“body-parser”节点模块。
npm install mongoose --save
Mongoose 是一个对象文档建模 (ODM) 层,它位于 Node 的 MongoDB 驱动程序的顶部。
app.js这是主要的可执行应用程序文件
app.js
var express=require("express");
var bodyParser=require("body-parser");
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/gfg');
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('signup_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");
index.html
Signup Form
signup_success.html
Signup Form
Signup Successful
style.css
.main{
padding:20px;
font-family: 'Helvetica', serif;
box-shadow: 5px 5px 7px 5px #888888;
}
.main h1{
font-size: 40px;
text-align:center;
font-family: 'Helvetica', serif;
}
input{
font-family: 'Helvetica', serif;
width: 100%;
font-size: 20px;
padding: 12px 20px;
margin: 8px 0;
border: none;
border-bottom: 2px solid #767474;
}
input[type=submit] {
font-family: 'Helvetica', serif;
width: 100%;
background-color: #767474;
border: none;
color: white;
padding: 16px 32px;
margin: 4px 2px;
border-radius: 10px;
}
启动 MongoDB。
运行 app.js 文件
node app.js
转到浏览器并打开 http://127.0.0.1:3000/
填写以上表格
这将在 MongoDB 中添加一个名为“David Smith”的记录。
让我们在 MongoDB 中检查相同的记录。
该记录现在保存在“详细信息”集合中的“gfg”数据库中。