Hexo博客添加GitHub评论功能

做一个有温度和有干货的技术分享作者 —— Qborfy

背景

其实从今年开始运营这个博客,我一直想增加一些新的交互功能,如:评论,之前一直有些问题没搞定,现在终于通过 Google 搜索解决问题了, 其实也算是每天学习一些新东西。

解决问题:给 Hexo 博客新增 Github评论功能

为什么选择 Github 呢?是因为 Github 对于偏向开发人员基本上属于一个必注册网站,而我博客的内容又偏向于技术,所以才会采取这个。

Gitalk

介绍

引入 Github评论功能,网上有很多现成的方案,这里就一一列举了,我采用了最主流的库——Gitalk.js,教程详细,不仅仅只能用于 Hexo,还可以适用于任何网站。

Gitalk 是一个基于 GitHub Issue 和 Preact 开发的评论插件。 —— Gitalk.js

使用

使用起来也非常简单,其实就是页面找个放置评论的位置,将对应资源引入,然后直接初始化使用即可。代码如下:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<div id="gitalk-container"></div>
<script>
var gitalk = new Gitalk({
clientID: 'GitHub Application Client ID', // 申请的GitHub Application Client ID.
clientSecret: 'GitHub Application Client Secret', // 申请的GitHub Application Client Secret.
repo: 'GitHub repo', // 这里填写 Github的仓库名
owner: 'GitHub repo owner', // 这里填写 Github的账户名
admin: ['GitHub repo owner and collaborators, only these guys can initialize github issues'], // 这里填写 Github的账户名
id: location.pathname, // Ensure uniqueness and length less than 50
distractionFreeMode: false // 类似 Facebook 的无干扰模式
})
gitalk.render('gitalk-container')
</script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
  <script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>

<div id="gitalk-container"></div>

<script>
var gitalk = new Gitalk({
  clientID: 'GitHub Application Client ID', //  申请的GitHub Application Client ID.
  clientSecret: 'GitHub Application Client Secret',  //  申请的GitHub Application Client Secret.
  repo: 'GitHub repo', //  这里填写 Github的仓库名
  owner: 'GitHub repo owner',  //  这里填写 Github的账户名
  admin: ['GitHub repo owner and collaborators, only these guys can initialize github issues'], //  这里填写 Github的账户名
  id: location.pathname,      // Ensure uniqueness and length less than 50
  distractionFreeMode: false  // 类似 Facebook 的无干扰模式

})

gitalk.render('gitalk-container')
</script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css"> <script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script> <div id="gitalk-container"></div> <script> var gitalk = new Gitalk({ clientID: 'GitHub Application Client ID', // 申请的GitHub Application Client ID. clientSecret: 'GitHub Application Client Secret', // 申请的GitHub Application Client Secret. repo: 'GitHub repo', // 这里填写 Github的仓库名 owner: 'GitHub repo owner', // 这里填写 Github的账户名 admin: ['GitHub repo owner and collaborators, only these guys can initialize github issues'], // 这里填写 Github的账户名 id: location.pathname, // Ensure uniqueness and length less than 50 distractionFreeMode: false // 类似 Facebook 的无干扰模式 }) gitalk.render('gitalk-container') </script>

如何申请Github Application授权登录,只需要在这里申请即可,只需要注意信任域名为自己的域名即可,如下图:

image.png

hexo使用

yilia-plus主题为例子,其他主题只需要放到对应位置即可,具体步骤如下所示:

  1. 在文件夹layout/_partial/post新增文件 gitalk.ejs,内容如下:
<div id="gitalk-container" style="padding: 0px 30px 0px 30px;"></div>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script type="text/javascript">
if(<%=theme.gitalk.enable%>){
var gitalk = new Gitalk({
clientID: '<%=theme.gitalk.ClientID%>',
clientSecret: '<%=theme.gitalk.ClientSecret%>',
repo: '<%=theme.gitalk.repo%>',
owner: '<%=theme.gitalk.githubID%>',
admin: ['<%=theme.gitalk.adminUser%>'],
id: '<%= page.date %>',
distractionFreeMode: '<%=theme.gitalk.distractionFreeMode%>',
proxy: 'https://test.com/proxy', // 这个是坑(Gitalk 本身提供了代理服务,但是国内经常无法访问),由于Github 采用的 OAuth 协议,所以需要我们自己写一套服务去支撑
})
gitalk.render('gitalk-container')
}
</script>
<div id="gitalk-container" style="padding: 0px 30px 0px 30px;"></div> 

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script type="text/javascript">

if(<%=theme.gitalk.enable%>){
  var gitalk = new Gitalk({
    clientID: '<%=theme.gitalk.ClientID%>',
    clientSecret: '<%=theme.gitalk.ClientSecret%>',
    repo: '<%=theme.gitalk.repo%>',
    owner: '<%=theme.gitalk.githubID%>',
    admin: ['<%=theme.gitalk.adminUser%>'],
    id: '<%= page.date %>',
    distractionFreeMode: '<%=theme.gitalk.distractionFreeMode%>',
    proxy: 'https://test.com/proxy', // 这个是坑(Gitalk 本身提供了代理服务,但是国内经常无法访问),由于Github 采用的 OAuth 协议,所以需要我们自己写一套服务去支撑
})
gitalk.render('gitalk-container') 
}
</script>
<div id="gitalk-container" style="padding: 0px 30px 0px 30px;"></div> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css"> <script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script> <script type="text/javascript"> if(<%=theme.gitalk.enable%>){ var gitalk = new Gitalk({ clientID: '<%=theme.gitalk.ClientID%>', clientSecret: '<%=theme.gitalk.ClientSecret%>', repo: '<%=theme.gitalk.repo%>', owner: '<%=theme.gitalk.githubID%>', admin: ['<%=theme.gitalk.adminUser%>'], id: '<%= page.date %>', distractionFreeMode: '<%=theme.gitalk.distractionFreeMode%>', proxy: 'https://test.com/proxy', // 这个是坑(Gitalk 本身提供了代理服务,但是国内经常无法访问),由于Github 采用的 OAuth 协议,所以需要我们自己写一套服务去支撑 }) gitalk.render('gitalk-container') } </script>
  1. 在主题中找到layout/_partial/post/article.ejs中想放置评论位置,加入判断是否启用 gitalk,代码如下:
<% if(theme.gitalk.enable){ %>
<%- partial('post/gitalk', {
key: post.slug,
title: post.title,
url: config.url+url_for(post.path)
}) %>
<% } %>
<% if(theme.gitalk.enable){ %>
  <%- partial('post/gitalk', {
      key: post.slug,
      title: post.title,
      url: config.url+url_for(post.path)
    }) %>
  <% } %>
<% if(theme.gitalk.enable){ %> <%- partial('post/gitalk', { key: post.slug, title: post.title, url: config.url+url_for(post.path) }) %> <% } %>
  1. 在主题根目录配置文件_config.yml 打开gitalk配置,如下:
#6、gitalk评论
gitalk:
enable: true
githubID: xxxxxx # 配置项基本于 GitTalk保持一致
repo: 'xxxxx'
ClientID: 'xxxxxx'
ClientSecret: 'xxxxx'
adminUser: xxxxx
distractionFreeMode: true
#6、gitalk评论
gitalk:
  enable:  true
  githubID:  xxxxxx  # 配置项基本于 GitTalk保持一致
  repo:  'xxxxx'
  ClientID:  'xxxxxx'
  ClientSecret:  'xxxxx'
  adminUser:  xxxxx
  distractionFreeMode: true
#6、gitalk评论 gitalk: enable: true githubID: xxxxxx # 配置项基本于 GitTalk保持一致 repo: 'xxxxx' ClientID: 'xxxxxx' ClientSecret: 'xxxxx' adminUser: xxxxx distractionFreeMode: true

遇到的问题

Gitalk 提示 “NetError”

其实是 Gitalk 内置了 proxy 代理服务去请求完成 Github OAuth 鉴权服务,但是由于国内会经常无法正常请求该代理服务,所以需要我们自己去完成 Github OAuth 鉴权,这里我简单写了一下代码,如下所示:

const koa = require('koa')
const bodyParser = require('koa-bodyparser')
const router = require('koa-router')()
const axios = require('axios')
// github application的配置
const config = {
client_id: 'xxxxx',
client_secret: 'xxxxxxxxx',
}
const app = new koa()
app.use(bodyParser())
router.post('/proxy', async (ctx, next) => {
// 获取Github OAuth鉴权回调的 code 值
const { code } = ctx.request.body
console.log('code', code)
const params = {
client_id: config.client_id,
client_secret: config.client_secret,
code: code
}
try {
const res = await axios.post('https://github.com/login/oauth/access_token', params)
const access_token = res.data.split('&')[0].split('=')[1]
console.log('res.data', res.data)
// 请求成功后返回access_token 去获取 Github 相关信息
ctx.body = {
access_token
}
} catch (err) {
console.log(err)
ctx.body = { err: err }
}
})
app.use(router.routes())
app.listen(3003, () => {
console.log('server is running at http://localhost:3003')
})
const koa = require('koa')
const bodyParser = require('koa-bodyparser')
const router = require('koa-router')()

const axios = require('axios')
// github application的配置
const config = {
    client_id: 'xxxxx',
    client_secret: 'xxxxxxxxx',
}

const app = new koa()
app.use(bodyParser())

router.post('/proxy', async (ctx, next) => {
    // 获取Github OAuth鉴权回调的 code 值
    const { code } = ctx.request.body
    console.log('code', code)
    const params = {
        client_id: config.client_id,
        client_secret: config.client_secret,
        code: code
    }
    try {
        const res = await axios.post('https://github.com/login/oauth/access_token', params)
        const access_token = res.data.split('&')[0].split('=')[1]
        console.log('res.data', res.data)
        // 请求成功后返回access_token 去获取 Github 相关信息
        ctx.body = {
            access_token
        }
    } catch (err) {
        console.log(err)
        ctx.body = { err: err }
    }

})

app.use(router.routes())

app.listen(3003, () => {
    console.log('server is running at http://localhost:3003')
})
const koa = require('koa') const bodyParser = require('koa-bodyparser') const router = require('koa-router')() const axios = require('axios') // github application的配置 const config = { client_id: 'xxxxx', client_secret: 'xxxxxxxxx', } const app = new koa() app.use(bodyParser()) router.post('/proxy', async (ctx, next) => { // 获取Github OAuth鉴权回调的 code 值 const { code } = ctx.request.body console.log('code', code) const params = { client_id: config.client_id, client_secret: config.client_secret, code: code } try { const res = await axios.post('https://github.com/login/oauth/access_token', params) const access_token = res.data.split('&')[0].split('=')[1] console.log('res.data', res.data) // 请求成功后返回access_token 去获取 Github 相关信息 ctx.body = { access_token } } catch (err) { console.log(err) ctx.body = { err: err } } }) app.use(router.routes()) app.listen(3003, () => { console.log('server is running at http://localhost:3003') })

参考资料

© 版权声明
THE END
喜欢就支持一下吧
点赞0

Warning: mysqli_query(): (HY000/3): Error writing file '/tmp/MYl7MrKV' (Errcode: 28 - No space left on device) in /www/wwwroot/583.cn/wp-includes/class-wpdb.php on line 2345
admin的头像-五八三
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

图形验证码
取消
昵称代码图片