曾经憧憬过 發表於 2022-11-24 18:37:00

uniapp 微信公众号开发 本地开发测试 本地接口联调

<h3 id="1-条件">1. 条件</h3>
<ul>
<li>本地一个uniapp的H5项目(本地运行 localhost:8080)</li>
<li>本地一个webservice接口项目(本地运行 127.0.0.1:9999)</li>
</ul>
<blockquote>
<p>目的:<br>
因微信公众号没有提供良好的测试体验环境,每次测试时又需要授权域名,而且必须是https的。我们也不方便映射一个域名到自己本机(局域网环境不一定有固定的公网ip)<br>
为了完成使用localhost也能在本地开发和调试微信公众号H5,记录一下自己的实施方案</p>
</blockquote>
<h3 id="2-准备一个https域名testwxh5poemfarcom">2. 准备一个https域名(test.wxh5.poemfar.com)</h3>
<blockquote>
<p>微信公共公众号配置业务域名需要https</p>
</blockquote>
<ul>
<li>公众号后台下载验证文件上传到该域名的根目录下(这里是我自己准备的linux服务器和nginx,相关配置这里不详述,如果这块条件自己不具备,可联系我免费帮忙验证,这样你可以共用我这个方向代理的域名进行本地测试)</li>
<li>填写业务域名、jsapi安全域名、网页授权域名</li>
<li>验证完成</li>
</ul>
<h3 id="3-反向代理该域名到本地站点">3. 反向代理该域名到本地站点</h3>
<blockquote>
<p>这里有好几个方案,如:nginx、设置本机host和端口转发、其他proxy。我这里是mac,使用最简单的hosts和端口转发来实现<br>
基本原理:hosts转发上一步的域名到127.0.0.1,然后使用端口转发8080到80<br>
nginx方案参考:https://blog.51cto.com/u_15570408/5205299</p>
</blockquote>
<ul>
<li>设置hosts(mac os)</li>
</ul>
<pre><code>sudo vim /etc/hosts

# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.Do not change this entry.
##
127.0.0.1       localhost
255.255.255.255 broadcasthost
::1               localhost
127.0.0.1       test.wxh5.poemfar.com
</code></pre>
<ul>
<li>测试一下,访问:http://test.wxh5.poemfar.com:8080</li>
</ul>
<blockquote>
<p>这里如果报错:Invalid Host header<br>
则是因为新版的webpack-dev-server出于安全考虑,默认检查hostname,如果hostname不是配置内的,将中断访问。<br>
解决办法:<br>
在manifest.json中配置:devServer:</p>
</blockquote>
<h3 id="通过mac的pf实现端口转发">通过mac的pf实现端口转发</h3>
<ul>
<li>pf.conf中增加:rdr on lo0 inet proto tcp from any to 127.0.0.1 port 80 -&gt; 127.0.0.1 port 8080</li>
</ul>
<pre><code>sudo vim /etc/pf.conf

#
# com.apple anchor point
#
scrub-anchor "com.apple/*"
nat-anchor "com.apple/*"
rdr-anchor "com.apple/*"
# 加入下面这行
rdr on lo0 inet proto tcp from any to 127.0.0.1 port 80 -&gt; 127.0.0.1 port 8080

dummynet-anchor "com.apple/*"
anchor "com.apple/*"
load anchor "com.apple" from "/etc/pf.anchors/com.apple"
</code></pre>
<ul>
<li>重新加载配置</li>
</ul>
<pre><code>sudo pfctl -f /etc/pf.conf
</code></pre>
<blockquote>
<p>输出:</p>
</blockquote>
<pre><code>pfctl: Use of -f option, could result in flushing of rules
present in the main ruleset added by the system at startup.
See /etc/pf.conf for further details.

No ALTQ support in kernel
ALTQ related functions disabled
</code></pre>
<p>表示成功了。</p>
<ul>
<li>启动(重启电脑后需要重新执行这个命令)</li>
</ul>
<pre><code>sudo pfctl -e
</code></pre>
<blockquote>
<p>输出:</p>
</blockquote>
<pre><code>No ALTQ support in kernel
ALTQ related functions disabled
pf enabled
</code></pre>
<p>表示生效了。</p>
<ul>
<li>测试:http://test.wxh5.poemfar.com<br>
微信授权已能正常返回code,成功!</li>
</ul>
<p>参考:https://blog.csdn.net/liushijun_/article/details/111563881</p><br><br>
来源:https://www.cnblogs.com/Denny_Yang/p/16922836.html
頁: [1]
查看完整版本: uniapp 微信公众号开发 本地开发测试 本地接口联调