Microblog 的demo终于用Nodejs调试成功了
Microblog 的demo终于用Nodejs调试成功了
Microblog 的demo终于用Nodejs调试成功了
经过几天的努力,我终于将一个简单的 Microblog(微型博客)的demo用 Node.js 调试成功了。这是一个非常有趣的项目,不仅让我加深了对 Node.js 的理解,还让我体验到了使用 Node.js 构建 Web 应用的乐趣。
项目结构
首先,我们来看一下项目的结构:
/microblog-demo
├── app.js
├── package.json
├── public
│ ├── index.html
│ └── styles.css
├── routes
│ └── blog.js
└── views
└── index.ejs
安装依赖
在项目根目录下运行以下命令安装所需的 npm 包:
npm init -y
npm install express ejs body-parser
主文件 app.js
接下来是我们的主文件 app.js
,它负责启动服务器并定义路由:
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));
// 引入路由模块
const blogRouter = require('./routes/blog');
app.use('/blog', blogRouter);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
路由文件 routes/blog.js
接下来是路由文件 routes/blog.js
,它定义了如何处理请求:
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
// 假设从数据库获取数据
const posts = [
{ id: 1, title: 'Hello World', content: 'This is my first post.' },
{ id: 2, title: 'Node.js Basics', content: 'Learning Node.js basics.' }
];
res.render('index', { posts });
});
router.post('/create', (req, res) => {
const { title, content } = req.body;
// 假设保存到数据库
console.log('New Post:', title, content);
res.redirect('/blog');
});
module.exports = router;
视图文件 views/index.ejs
最后是视图文件 views/index.ejs
,它用于渲染页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Microblog</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<div class="container">
<h1>Microblog</h1>
<form action="/blog/create" method="POST">
<input type="text" name="title" placeholder="Title" required>
<textarea name="content" placeholder="Content" required></textarea>
<button type="submit">Post</button>
</form>
<% posts.forEach(post => { %>
<div class="post">
<h2><%= post.title %></h2>
<p><%= post.content %></p>
</div>
<% }) %>
</div>
</body>
</html>
通过以上步骤,你就可以创建一个简单的 Microblog DEMO,并使用 Node.js 运行它。这个例子展示了如何使用 Express 框架构建基本的 Web 应用,包括路由、表单处理以及模板渲染。希望这对你有所帮助!
分享一下过程嘛
我也找了半天,这里有另外一个例子,https://code.google.com/p/microblog-nodejs/
那个教材过时了,如果你们都用最新的库去运行的话。
想要调试成功,严格安装教材上对应版本的库。
初学者往往不注意版本。
可以按照书上的来做,如果有问题,看看相应的文档吧,这样最好了。
Microblog 的 demo 终于用 Node.js 调试成功了
今天终于成功地调试了一个基于 Node.js 的微博客(Microblog)demo。这是一个非常简单的项目,主要功能包括发布、查看和删除微博。通过这个项目,我更好地理解了 Express 框架和 MongoDB 数据库的使用。
技术栈:
- Node.js:后端开发的基础框架。
- Express.js:一个简洁而灵活的 Node.js 网络应用框架。
- MongoDB:文档数据库,用于存储微博数据。
- EJS:一个简单易用的模板引擎。
示例代码:
-
安装依赖 首先需要安装一些必要的 npm 包,例如
express
、mongoose
和ejs
。npm install express mongoose ejs
-
设置 Express 应用
// app.js const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const app = express(); const PORT = 3000; // 连接 MongoDB mongoose.connect('mongodb://localhost:27017/microblog', { useNewUrlParser: true, useUnifiedTopology: true }); // 设置模板引擎 app.set('view engine', 'ejs'); // 中间件 app.use(bodyParser.urlencoded({ extended: true })); // 路由 app.get('/', (req, res) => { res.render('index'); }); app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
-
创建微博模型
// models/Microblog.js const mongoose = require('mongoose'); const microblogSchema = new mongoose.Schema({ content: String, createdAt: { type: Date, default: Date.now } }); module.exports = mongoose.model('Microblog', microblogSchema);
-
创建路由处理发布微博
// routes/microblogs.js const express = require('express'); const router = express.Router(); const Microblog = require('../models/Microblog'); router.post('/create', async (req, res) => { try { await Microblog.create(req.body); res.redirect('/'); } catch (err) { console.error(err); res.status(500).send('Error creating microblog'); } }); module.exports = router;
-
创建视图文件
<!-- views/index.ejs --> <!DOCTYPE html> <html> <head> <title>Microblog</title> </head> <body> <h1>Microblog</h1> <form action="/create" method="POST"> <textarea name="content" rows="4" cols="50"></textarea> <br/> <button type="submit">发布</button> </form> <ul> <% microblogs.forEach(microblog => { %> <li><%= microblog.content %> - <%= microblog.createdAt.toLocaleString() %></li> <% }) %> </ul> </body> </html>
通过上述代码,你可以看到一个基本的微博客系统是如何构建的。这个示例包括前端表单提交和后端处理逻辑,以及简单的页面展示。希望这些示例代码对你有所帮助!