Hexo使用国际版LeanCloud Valine评论连接失败

最近发现博客的评论系统(Leancloud)无法使用了,记录下解决过程。

问题展现

首先打开浏览器控制台,发现有连接错误:

尝试连接域名 https://us-api.leancloud.cn,结果域名已经失效了。去官方查看,发现 LeanCloud官方已不推荐使用通用域名

解决问题

网上很多教程都说直接修改配置文件,添加配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Valine.
# You can get your appid and appkey from https://leancloud.cn
# more info please open https://valine.js.org
valine:
enable: true
appid: appID
appkey: appKey
notify: true # mail notifier , https://github.com/xCss/Valine/wiki
verify: false # Verification code
placeholder: 说点什么吧~ # comment box placeholder
avatar: mm # gravatar style
guest_info: nick,mail # custom comment header
pageSize: 10 # pagination size
serverURLs: https://xxxxxxxx.api.lncldglobal.com

其中 serverURLs 可以通过官方控制台( 设置 - 应用凭证)中找到:

其实就是 https://{appid前8位}.api.lncldglobal.com

如果上述方案还未生效,需要修改主题下的 valine 评论模板文件,以 Next 主题为例,在 next/layout/_third-party/comments/ 中找到模板文件 valine.swig:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
{% if theme.valine.enable and theme.valine.appid and theme.valine.appkey %}
<script src="//code.bdstatic.com/npm/leancloud-storage@4.12.0/dist/av-min.js"></script>
<script src="//unpkg.com/valine/dist/Valine.min.js"></script>
<!-- <script src="/js/src/Valine.min.js"></script> -->

<script type="text/javascript">
var GUEST = ['nick','mail','link'];
var guest = '{{ theme.valine.guest_info }}';
guest = guest.split(',').filter(item=>{
return GUEST.indexOf(item)>-1;
});
new Valine({
el: '#comments' ,
verify: {{ theme.valine.verify }},
notify: {{ theme.valine.notify }},
appId: '{{ theme.valine.appid }}',
appKey: '{{ theme.valine.appkey }}',
placeholder: '{{ theme.valine.placeholder }}',
avatar:'{{ theme.valine.avatar }}',
guest_info:guest,
pageSize:'{{ theme.valine.pageSize }}' || 10,
serverURLs: '{{ theme.valine.serverURLs }}', // 添加这行,从配置文件中读取serverURLs
});

//增加以下六行代码去除 power by valine
var infoEle = document.querySelector('#comments .info');
if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0){
infoEle.childNodes.forEach(function(item) {
item.parentNode.removeChild(item);
});
}
</script>
{% endif %}

在方法 new Valine() 中添加:

1
serverURLs: '{{ theme.valine.serverURLs }}',

同时,最好升级下相关 js 版本:

1
2
<script src="//code.bdstatic.com/npm/leancloud-storage@4.12.0/dist/av-min.js"></script>
<script src="//unpkg.com/valine/dist/Valine.min.js"></script>

参考

修改Leancloud国际版域名