使用Node.js、Bootstrap和MongoDB构建简单的初级应用
Node.js是一个著名的开源环境,允许在浏览器之外运行JavaScript脚本。MERN和MEAN堆栈是两种最流行的组合,可以帮助您创建令人惊叹的应用程序。在本文中,我们将使用Node.js、Bootstrap和MongoDB创建一个简单友好的联系表单应用。在开始项目之前,确保您的系统已安装Node.js和MongoDB。
项目结构:
步骤1: 创建一个项目文件夹并在你的IDE中打开该文件夹。
首先,使用IDE终端中的 npm init 命令创建一个带有你提供的值的 package.json 文件。
npm init
您可以自定义在初始化过程中询问的问题和创建的字段,或者保留默认设置。处理完成后,您会在项目文件夹中找到 package.json 文件。
步骤2: 接下来,在项目文件夹中创建 index.js 文件,这将是应用的入口点。
步骤3: 现在使用 npm 命令安装依赖项 express 、 mongoose 和 nodemon 。
npm install express mongoose nodemon
安装依赖项需要一些时间,等待安装完成后,在dependencies下的package.json文件中将创建一个名为 node_modules 的文件夹,您将找到所有已安装依赖项的名称和版本。
步骤4: 我们接下来将打开 index.js文件,并使用以下代码创建一个简单的express app。
// Importing express module
const express = require("express");
// Importing mongoose module
const mongoose = require("mongoose");
const port = 80;
const app = express();
// Handling the get request
app.get("/", (req, res) => {
res.send("Hello World");
});
// Starting the server on the 80 port
app.listen(port, () => {
console.log(`The application started
successfully on port ${port}`);
});
这段代码创建了一个简单的express应用程序,启动了一个服务器并监听 80端口 用于连接。该应用程序对 “/” 的请求作出 “Hello World” 的响应。
步骤5: 要运行代码,请打开终端并键入
nodemon index.js
步骤6: 然后打开您的浏览器,使用 http://localhost 或简单地输入 localhost 来访问服务器本身。
该页显示 “Hello World” ,这意味着我们的Express应用程序正常工作。
步骤7: 现在,我们需要添加两行代码,因为我们将需要 express.json() 和 express.urlencoded() 来处理POST和PUT请求。 Express 为我们提供了中间件来处理请求体中的传入数据对象。在POST和PUT请求中,我们将数据对象发送到服务器并要求服务器接受或存储该数据对象,该数据对象包含在该请求的req.body中。
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
步骤8: 在项目文件夹内创建一个名为 public 的文件夹。我们将在项目的 public 目录中创建所有静态HTML文件。
// For serving static html files
app.use(express.static('public'));
步骤9: 现在我们将使用以下代码连接到mongoose数据库。该项目的数据库名称为 projectDG
mongoose.connect("mongodb://localhost/projectDG", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
let db = mongoose.connection;
步骤10: 接下来,我们将定义一个用于将联系表单数据保存到我们的数据库的post方法。我们定义了我们的数据对象,并在这里创建了一个名为 users 的集合。成功插入数据后,我们将重定向到 formSubmitted.html
这是index.js文件的主要部分,其中将处理post请求,并从客户端请求正确地将数据传输到主数据库服务器。
app.post("/formFillUp", (req, res) => {
const name = req.body.name;
const reason = req.body.reason;
const email = req.body.email;
const phone = req.body.phone;
const city = req.body.city;
const state = req.body.state;
const addressline = req.body.addressline;
const data = {
name: name,
reason: reason,
email: email,
phone: phone,
city: city,
state: state,
addressline: addressline,
};
db.collection("users").insertOne(data,
(err, collection) => {
if (err) {
throw err;
}
console.log("Data inserted successfully!");
});
return res.redirect("formSubmitted.html");
});
最终的index.js代码如下:
文件名:index.js
const express = require("express");
const mongoose = require("mongoose");
const port = 80;
const app = express();
mongoose.connect("mongodb://localhost/projectDG", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
let db = mongoose.connection;
app.use(express.json());
// For serving static HTML files
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.get("/", (req, res) => {
res.set({
"Allow-access-Allow-Origin": "*",
});
// res.send("Hello World");
return res.redirect("index.html");
});
app.post("/formFillUp", (req, res) => {
const name = req.body.name;
const reason = req.body.reason;
const email = req.body.email;
const phone = req.body.phone;
const city = req.body.city;
const state = req.body.state;
const addressline = req.body.addressline;
const data = {
name: name,
reason: reason,
email: email,
phone: phone,
city: city,
state: state,
addressline: addressline,
};
db.collection("users").insertOne(
data, (err, collection) => {
if (err) {
throw err;
}
console.log("Data inserted successfully!");
});
return res.redirect("formSubmitted.html");
});
app.listen(port, () => {
console.log(`The application started
successfully on port ${port}`);
});
步骤11: 现在我们将在 public 文件夹内创建 index.html, formSubmittedhtml 和 style.css 文件。
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,
initial-scale=1, shrink-to-fit=no" />
<!-- Bootstrap CSS -->
<link rel="stylesheet" href=
"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity=
"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous" />
<link rel="stylesheet" href="./style.css" />
<link href=
"https://fonts.googleapis.com/css2?family=Poppins&display=swap"
rel="stylesheet" />
</head>
<body>
<div class="container mt-3">
<br />
<h1>Contact Us</h1>
<br />
<form action="/formFillUp" method="POST">
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputName"
style="font-size: 23px">
Name
</label>
<input type="text" class="form-control"
id="name" name="name" />
</div>
<div class="form-group col-md-6">
<label for="inputReason"
style="font-size: 23px">
Reason for contacting
</label>
<input type="text" class="form-control"
id="reason" name="reason" />
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail"
style="font-size: 23px">
Email
</label>
<input type="email" class="form-control"
id="inputEmail" name="email" />
</div>
<div class="form-group col-md-6">
<label for="inputPhone"
style="font-size: 23px">Phone
</label>
<input type="text" class="form-control"
id="inputPhone" name="phone" />
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputCity"
style="font-size: 23px">City
</label>
<input type="text" class="form-control"
id="inputCity" name="city" />
</div>
<div class="form-group col-md-6">
<label for="inputState"
style="font-size: 23px">State
</label>
<input type="text" class="form-control"
id="inputState" name="state" />
</div>
</div>
<div class="form-group">
<label for="inputAddress"
style="font-size: 23px">Address</label>
<input type="text" class="form-control"
id="inputAddress" name="addressline" />
</div>
<button type="submit" class="btn btn-primary">
Submit
</button>
</form>
</div>
</body>
</html>
输出:
formSubmitted.html
<!DOCTYPE html>
<html>
<head>
<title>Form Submitted Successfully</title>
<link rel="stylesheet" href="./style.css" />
<link href=
"https://fonts.googleapis.com/css2?family=Poppins&display=swap"
rel="stylesheet" />
</head>
<body>
<div class="containerFormSubmittedMessage">
<h1>Form Submitted Successfully!</h1>
Thank you for contacting us! Our
team will mail you shortly.
</div>
</body>
</html>
输出:
style.css
body {
background-image: linear-gradient(120deg,
#9de7fa 0%,
#f89fba 100%);
color: white;
font-family: "Poppins", sans-serif;
min-height: 100vh;
}
.btn-primary {
color: #fff;
background-color: #f89fba;
border-color: #f89fba;
}
.containerFormSubmittedMessage {
display: flex;
flex-direction: column;
margin: auto;
justify-content: center;
align-items: center;
height: 200px;
border: 3px solid whitesmoke;
}
步骤12: 创建完这三个文件后,我们的项目差不多完成了。现在我们将开始MongoDB。打开Windows Powershell窗口,然后输入以下命令 mongod。
mongod
打开另一个Windows Powershell窗口,并输入以下命令
mongo
mongo
步骤13: 打开你的IDE,在终端中输入 nodemon index.js 来启动应用程序。前往 localhost 。
注意: 成功插入的数据将在正确处理POST请求后打印出来。
- 填写联系表单的详细信息。表单成功提交后,您将被重定向到 formSubmitted.html ,从 index.html 页面。
- 现在,为了检查我们在联系表单中输入的数据是否已保存到 projectDG 数据库中,我们将在第二个 Windows Powershell 窗口中使用以下命令。
此命令列出了 MongoDB 中的所有数据库:
show dbs
这个命令将让我们切换到我们的数据库:
use projectDG
这个命令将会检查集合中某个特定数据:
db.users.find()
我们可以清楚地看到数据已经被插入到MongoDB数据库中。