解决使用LeanCloud国际版时网站文章浏览次数不显示的bug
By Long Luo
之前个人网站文章阅读次数存储一直在Leancloud上,由于去年国内版要求网站必须备案才能使用之后,个人网站的浏览次数一直是不可用状态。几个月前切换到国际版,但是切换之后浏览次数一直是空白null
值,正常应该是0
,数据也不会更新。
后台查看Counter
数据,也一直是没有数据的状态。当时花费了时间去检查,试图找到问题所在,当时还是怀疑LeanCloud国际版后台接口API的问题,但一直没能解决这个问题。
今天下午从原理入手,分析每个可能的步骤,找到了问题原因,在此记录下解决问题的过程。
如何显示阅读次数?
网站使用的是Hexo + Next主题,可以使用3种方式显示阅读次数:1. Leancloud; 2. FireStore; 3. Busuanzi
FireStore由于需要翻墙,尝试过发现不可行;
Busuanzi虽然也可以,设置之后发现首页数据显示紊乱,而且不准,使用了一段时间之后放弃;
LeanCloud是最合适的,数据也可以很方便的进行迁移。
在Next主题配置_config.yml
文件中,可以设置使用哪种计数方式。注意文章阅读次数只能设置一个为true,否则页面会显示多个阅读次数。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24leancloud_visitors:
enable: true
app_id: # <your app id> hdPFnwkCdbHRj5Q3OQk5vNJQ-gzGzoHsz
app_key: # <your app key> p2mNUdDbqxrxOYMjs1xiS0zM
# Another tool to show number of visitors to each article.
# Visit https://console.firebase.google.com/u/0/ to get apiKey and projectId.
# Visit https://firebase.google.com/docs/firestore/ to get more information about firestore.
firestore:
enable: false
collection: articles # Required, a string collection name to access firestore database
apiKey: # Required
projectId: # Required
# Show Views / Visitors of the website / page with busuanzi.
# For more information: http://ibruce.info/2015/04/04/busuanzi/
busuanzi_count:
enable: true
total_visitors: true
total_visitors_icon: fa fa-user
total_views: true
total_views_icon: fa fa-eye
post_views: false
post_views_icon: fa fa-eye
如何读写阅读次数的?
这里以LeanCloud为例来说明阅读次数是如何读写的。首先打开网站首页,查看源代码:1
2
3
4
5<span class="post-meta-item-icon">
<i class="far fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读次数:</span>
<span class="leancloud-visitors-count"></span>
可以看出,阅读次数是通过leancloud-visitors-count
这个class
的值来显示的,搜索leancloud-visitors-count
可以在网页的js
代码中找到:1
2
3
4function leancloudSelector(url) {
url = encodeURI(url);
return document.getElementById(url).querySelector('.leancloud-visitors-count');
}
那么这段js
代码在哪里呢?