11/05更新:基于 Nodejs + express + mongodb 的个人博客程序

11/05更新:基于 Nodejs + express + mongodb 的个人博客程序

Application Error An error occurred in the application and your page could not be served. Please try again in a few moments.

If you are the application owner, check your logs for details.

。。。

44 回复

当然,我可以帮助你编写一个基于Node.js、Express和MongoDB的简单个人博客程序。以下是一个简化的示例,包括如何设置项目、创建模型、路由以及一些基本的CRUD操作。

1. 初始化项目

首先,确保你已经安装了Node.js和npm。然后,创建一个新的项目目录并初始化npm:

mkdir myblog
cd myblog
npm init -y

安装所需的依赖包:

npm install express mongoose body-parser ejs

2. 创建项目结构

创建以下文件和文件夹结构:

myblog/
├── app.js
├── models/
│   └── Post.js
├── views/
│   ├── index.ejs
│   └── post.ejs
└── routes/
    └── posts.js

3. 配置数据库连接

app.js中配置MongoDB连接:

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = express();

// Connect to MongoDB
mongoose.connect('mongodb://localhost/myblog', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));

const Post = require('./models/Post');

// Routes
const postsRouter = require('./routes/posts');
app.use('/posts', postsRouter);

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

4. 定义模型

models/Post.js中定义博客文章模型:

const mongoose = require('mongoose');

const postSchema = new mongoose.Schema({
  title: { type: String, required: true },
  content: { type: String, required: true },
  createdAt: { type: Date, default: Date.now },
});

module.exports = mongoose.model('Post', postSchema);

5. 创建路由

routes/posts.js中添加路由逻辑:

const express = require('express');
const router = express.Router();
const Post = require('../models/Post');

router.get('/', async (req, res) => {
  const posts = await Post.find().sort({ createdAt: 'desc' });
  res.render('index', { posts });
});

router.get('/new', (req, res) => {
  res.render('post');
});

router.post('/', async (req, res) => {
  const post = new Post({
    title: req.body.title,
    content: req.body.content,
  });

  try {
    await post.save();
    res.redirect('/');
  } catch (err) {
    console.error(err);
    res.status(500).send('An error occurred');
  }
});

module.exports = router;

6. 视图模板

views/index.ejs中创建首页模板:

<!DOCTYPE html>
<html>
<head>
  <title>My Blog</title>
</head>
<body>
  <h1>My Blog</h1>
  <ul>
    <% posts.forEach(post => { %>
      <li>
        <a href="/posts/<%= post._id %>"><%= post.title %></a>
      </li>
    <% }) %>
  </ul>
</body>
</html>

views/post.ejs中创建新文章表单:

<!DOCTYPE html>
<html>
<head>
  <title>New Post</title>
</head>
<body>
  <h1>New Post</h1>
  <form action="/posts" method="POST">
    <label>Title:</label><br>
    <input type="text" name="title"><br>
    <label>Content:</label><br>
    <textarea name="content"></textarea><br>
    <button type="submit">Submit</button>
  </form>
</body>
</html>

以上代码提供了一个简单的个人博客系统的基础结构,你可以根据需要进一步扩展功能。希望这对你有所帮助!


刚看了一下 log ,没有验证文件是否存在,转换就出问题鸟~

嘿嘿,遇到对手了,我也在用 node, express, markdown 做博客

发现用 JSON 文件做存储的话,在 Heroku 这样用 Git 部署的云平台会杯具,push 一下,先过的文章就没了。看来还是得换到 mongodb 去

一样在尝试用node, express, markdown 写博客,只是么有用json文件做持久,还是选mysql了。。

静态文件速度是快,不过还是建议扔mongo到里吧。

果断收藏~~~

存储改用 mongo 工程进行中。

更新存储为 mongodb,使用了 mongoskin

原来的版本还可以下载么

看起来不错,风格用的是哪个?

我个人是在github上搭的博客。write like a hacker. such as: [http://yansong.me](my blog)

说真的,我自己觉得nodejs不适合用来搭博客的。wordpress已经很强大了,这种重复造轮子的做法很不可取。

也可能我说的都是错的;)

原来的版本废弃了。

呃,自己的。

没有适不适合这么一说吧,自己的小玩具而已。

给noderce加了评论功能。

Heroku 收费怎么样?

学习学习,O(∩_∩)O~

清爽!

现在换到 appfog 了, 这样的小应用,heroku 免费套餐也够用的。

刚刚试验了下,数据库不知道要怎么配???还有初始的管理员密码是??开启后,数据库连接报错连接不上。。新人求指导~~~谢谢

羞,我也是新人。 数据库连接,在 config.js 中最后一行,修改它。

exports.db = mongoskin.db(process.env.MONGOLAB_URI || “mongodb://localhost/noderce”);

另外,数据库的初始化还没做。捂脸。

所以你自己生成一个 md5 密码。然后

db.user.insert({name:‘admin’,password:‘21232f297a57a5a743894a0e4a801fc3’})

现在,就可以使用 admin admin 登录了。

会尽快加上初始化功能。

添加了数据库初始化功能

就用这个啦。。哈哈

Error: Cannot find module ‘gravatar’

不错,下下来看看

这个是要安装gravatar?

博客怎么发图片啊?楼主

由于现在的 appfog , openshift 之类的都不再提供持久存储了。所以没有考虑文件上传功能。 自己的找个可以直接外链的空间放吧。

楼主的站现在是放在独立空间上?? 我看您的图片不像是引外站的。。 目前也在做站 对于图片存储这里,也在烦空间问题。。。。

是的,偷偷放在国内的一台服务器上。

有只驴子写了部署在 openshift 的教程:http://hoperce.com/post/openshift-publish

新增一个主题。 shuixin,欢迎围观 https://github.com/willerce/noderce

哈哈,看来做这个东西的人不少哦,看了楼主的相当不错。刚入门nodejs不久,也正在做类似的一个https://github.com/Shaman05/node-blog,希望楼主多多指点 :)

是呀,适不适合做了才知道呢,呵呵。其实就算不适合,对于新手nodejser来说练手蛮不错的,还是能学到不少东西。

囧,我刚开始也是没有考虑到管理员账号创建的问题,后来单独写了个文件添加一个admin,然后删掉后重新部署。

cool, 但是 node_modules 不应该提交到库里

E:\nodejs>git clone git@github.com:willerce/noderce.git Cloning into ‘noderce’… Permission denied (publickey). fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.

克隆错误,应该怎么办?

用git协议克隆需要ssl权限,估计你没有配置。那就用http协议: git clone https://github.com/willerce/noderce.git

图片可以考虑放在七牛上面,标准用户有免费的额度,如下:

  • 免费存储空间10GB
  • 免费每月下载流量10GB
  • 免费每月PUT/DELETE 10万次请求
  • 免费每月GET 100万次请求

如果不介意的话,可以使用我的推荐链接http://portal.qiniu.com/signup?code=3lea5c9rk89jm

完全不介意。

这位楼主,若是我现在克隆一下 你会不会去告官?

根据你的描述,错误信息表明你的Node.js应用程序遇到了一个错误,并且无法提供服务。这类问题可能由多种原因引起,例如数据库连接失败、服务器配置错误、代码逻辑错误等。为了帮助你更好地定位问题,以下是一些常见的排查步骤:

1. 检查日志文件

确保你已经开启了详细的日志记录。Express应用通常会使用morgan这样的中间件来记录HTTP请求,MongoDB连接失败或查询错误也会被记录到控制台或日志文件中。

const morgan = require('morgan');
app.use(morgan('dev')); // 'dev'模式提供较详细的日志输出

检查这些日志文件,找到具体的错误信息,比如:

  • MongoDB连接错误
  • 查询语句错误
  • 文件路径错误

2. 确认数据库连接

确保你的MongoDB数据库运行正常,并且Express应用能够正确连接到数据库。你可以使用MongoDB的官方驱动程序或第三方库如mongoose来简化操作。

示例代码(使用Mongoose连接MongoDB):

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/blog', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    console.log("Connected to MongoDB");
});

3. 验证路由和控制器

确保所有API端点和处理函数都已正确实现并且没有逻辑错误。如果存在未捕获的异常或异步错误处理不当,也可能会导致服务中断。

示例代码(定义一个简单的Express路由):

const express = require('express');
const router = express.Router();

router.get('/posts', async (req, res) => {
    try {
        const posts = await Post.find(); // 假设Post是通过mongoose定义的模型
        res.json(posts);
    } catch (error) {
        res.status(500).send(error.message);
    }
});

module.exports = router;

4. 确保依赖项版本兼容

检查package.json中的依赖项是否与当前环境兼容。有时候,特定版本的库可能存在已知的问题或不兼容性。

5. 重启服务

尝试重启Node.js服务,有时临时的内存泄漏或其他问题可以通过重启解决。

希望这些建议能帮助你找到并解决问题!如果需要进一步的帮助,请提供更多关于错误的日志信息。

回到顶部