构建Node.js Web 应用:使用Express、EJS 和 Mongoose
在本篇博客文章中,我们将介绍如何使用Node.js的Express框架、EJS模板引擎和Mongoose库来构建一个简单的Web应用实例。
通过代码示例和详细解释,帮助读者了解如何结合这些工具来构建一个完整的Node.js Web 应用。
1. 准备工作
首先,确保你已经安装了Node.js和npm(Node.js 的包管理工具)。
然后创建一个新的文件夹作为我们的项目目录,并在命令行中执行以下命令,初始化一个新的Node.js项目:
npm init -y
2. 安装依赖
接下来,我们需要安装Express、EJS和Mongoose作为我们项目的依赖:
npm install express ejs mongoose
3. 创建Express 应用
在项目目录下创建一个名为app.js的文件,并编写以下代码:
const express = require('express');
const app = express();
const port = 3000;
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('index', { title: 'Express + EJS + Mongoose Example' });
});
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
});
4. 创建EJS视图
在项目目录下创建一个名为views的文件夹,并在其中创建一个名为index.ejs的文件,编写以下代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= title %></title>
</head>
<body>
<h1>Welcome to <%= title %></h1>
</body>
</html>
5. 使用Mongoose连接数据库
在app.js中添加Mongoose连接数据库的代码:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydb', {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => {
console.log('Connected to the database');
})
.catch((err) => {
console.error('Error connecting to the database', err);
});
代码示例
// 完整的app.js代码
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const port = 3000;
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('index', { title: 'Express + EJS + Mongoose Example' });
});
mongoose.connect('mongodb://localhost:27017/mydb', {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => {
console.log('Connected to the database');
})
.catch((err) => {
console.error('Error connecting to the database', err);
});
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
});
<!-- 完整的index.ejs代码 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= title %></title>
</head>
<body>
<h1>Welcome to <%= title %></h1>
</body>
</html>
总结
通过本文的介绍,我们学习了如何使用Node.js的Express框架、EJS模板引擎和Mongoose库来构建一个简单的Web应用实例。
通过这个示例,我们可以了解到如何快速搭建一个Node.js Web 应用的基本流程,以及如何使用EJS进行页面渲染,Mongoose进行数据库连接。
希望读者能够通过本文对Node.js的Web开发有更深入的了解,并能够在实际项目中灵活运用这些技术,构建出更加强大和可维护的Web应用。