21xrx.com
2024-06-03 04:22:53 Monday
登录
文章检索 我的文章 写文章
Node.js和Hexo:如何添加评论功能
2023-07-05 06:46:00 深夜i     --     --
Node js Hexo 添加评论功能

Node.js是一个基于Chrome V8引擎的轻量级JavaScript运行环境,可以用于服务器端编程。Hexo是一个基于Node.js的静态博客生成器,可以将Markdown文件转换为静态网页。本文将介绍如何在Hexo博客中添加评论功能,利用Node.js的Express框架。

1. 安装Hexo

首先,需要安装Hexo。可以使用npm来安装,命令如下:


npm install -g hexo

2. 安装Express

安装Express框架,可以使用以下命令:


npm install express --save

3. 安装其他依赖

为了添加评论功能,还需要安装其他依赖:


npm install body-parser --save

npm install cookie-parser --save

npm install express-session --save

npm install mongodb --save

4. 添加评论功能

在Hexo博客的项目目录下,创建一个名为“comments”的目录,用于存放评论数据。然后,在Hexo项目的根目录下,在命令行中输入以下命令:


hexo new page comments

这将创建一个名为“comments”的页面。然后,在“source/comments/index.md”文件中添加以下内容:


---

layout: false

---

{% include comments.html %}

该页面使用comments.html模板,用于显示评论。

在Hexo项目的“themes/<主题名称>/layout/_partial”目录下创建一个名为“comments”的目录,并在该目录下创建一个名为“comments.ejs”的文件。该文件用于显示评论和提交表单。

5. 连接数据库

评论需要存储到数据库中,可以使用MongoDB。在Node.js中,可以使用Mongoose来连接MongoDB。

在Hexo项目的根目录下,创建一个名为“config.json”的文件,加入以下内容:


 "mongoUrl": "mongodb://<username>:<password>@<hostname>:<port>/<database>"

其中, , , , and 是MongoDB的连接参数, 是要连接的数据库名称。

在Hexo项目的“themes/<主题名称>/layout/_partial/comments/comments.ejs”文件中,添加以下代码:


<% var mongoose = require('mongoose');

  mongoose.connect(config.mongoUrl);

  var commentsSchema = mongoose.Schema({

    name: String,

    email: String,

    comment: String,

    timestamp:

      type: Date,

    post_id: String

  });

  var Comment = mongoose.model('Comment', commentsSchema); %>

这将连接到MongoDB,并定义评论数据模型。

6. 编写服务器端代码

在Hexo项目的根目录下,创建一个名为“server.js”的文件。该文件用于定义Express服务器端代码。在该文件中,添加以下代码:


var express = require('express');

var app = express();

var bodyParser = require('body-parser');

var cookieParser = require('cookie-parser');

var session = require('express-session');

var MongoStore = require('connect-mongo')(session);

var mongoose = require('mongoose');

mongoose.connect(hexo.config.mongoUrl);

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));

app.use(cookieParser());

app.use(session({

  secret: 'secret-key',

  resave: false,

  saveUninitialized: false,

  store: new MongoStore(

    mongooseConnection: mongoose.connection

  )

}));

app.post('/comment', function(req, res) {

  var comment = new Comment(

    email: req.body.email);

  comment.save(function(err) {

    if (err) {

      console.log(err);

      res.json({ error: true });

    } else {

      res.json({ error: false });

    }

  });

});

app.listen(3000);

这段代码定义了一个Express应用,并监听端口3000。它使用body-parser中间件来解析POST请求中的JSON数据,使用cookie-parser和express-session中间件存储会话数据,并使用connect-mongo中间件将会话存储到MongoDB中。

7. 在Hexo中引用服务器端代码

在Hexo项目的“themes/<主题名称>/layout/_partial/comments/comments.ejs”文件中,添加以下代码:


<form id="comment-form">

  <input type="text" name="name" placeholder="Your Name" required>

  <input type="email" name="email" placeholder="Email Address" required>

  <textarea name="comment" placeholder="Leave a Comment" required></textarea>

  <input type="submit">

</form>

<script src="/js/jquery.min.js"></script>

<script type="text/javascript">

  $(function() {

    $('#comment-form').submit(function(e) {

      e.preventDefault();

      $.ajax({

        url: '/comment',

        method: 'POST',

        dataType: 'json',

        data: $(this).serialize(),

        success: function(data) {

          console.log(data);

          if (!data.error) {

            $('#comment-form')[0].reset();

            $('#comment-list').append(

              '<div class="comment">' +

              '<div class="name">' + data.name + '</div>' +

              '<div class="date">' + new Date(data.timestamp).toLocaleString() + '</div>' +

              '<div class="text">' + data.comment + '</div>' +

              '</div>'

            );

          }

        }

      });

    });

  });

</script>

该文件定义了一个包含提交评论表单的HTML代码,并使用jQuery提交表单数据。它还定义了在评论提交后显示评论的JavaScript代码。

8. 启动服务器

在命令行中运行以下命令,启动Node.js服务器:


node server.js

在浏览器中访问Hexo博客的“/comments”页面,应该可以看到评论表单。

在评论提交后,评论数据将存储到MongoDB中。可以在MongoDB的命令行中查看数据:


> use <database>

> db.comments.find()

在Hexo博客的评论页面中,还需要显示之前提交的评论。可以使用以下代码:


<% Comment.find({ post_id: hexo.page._id }).sort({ timestamp: 1 }).exec(function(err, comments) {

   if (err) return console.log(err);

   comments.forEach(function(comment) { %>

     <div class="comment">

       <div class="name"><%= comment.name %></div>

       <div class="date"><%= new Date(comment.timestamp).toLocaleString() %></div>

       <div class="text"><%= comment.comment %></div>

     </div>

   <% });

  });

%>

该代码在评论页面的HTML中,使用Mongoose从MongoDB中获取评论数据,并显示在页面上。

这样,就成功地在Hexo博客中添加了评论功能,利用Node.js的Express框架和MongoDB数据库。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复