一、问题:
开发小程序的时候有4个版本(开发、体验、审核、正式)。所以不同的环境要请求不同的后台。特别是审核版本,因为还要微信审核,如果请求错误,会被审核失败。因为生产环境是对应旧的后台版本,所以审核版本既不能调到后台生产环境,也不能跳到开发环境。
我们为了方便生产、审核2个版本小程序都去请求/prod。这里就要区别真实的请求到底是从生产、审核哪里来的。
二、解决思路。
微信给我们服务器发送请求wx.request的会带上一个referer的header参数。格式如下:
https://servicewechat.com/appId/version/page-frame.html其中appId是发送请求的小程序appId,version是小程序的版本。
开发、体验、审核版本中version值是0,开发工具中version值是devtools。正式版的version值是大于0的正整数,表示这个小程序发布到正式版多少次。例子如下:
开发版:https://servicewechat.com/小程序appId/0/page-frame.html体验版:https://servicewechat.com/小程序appId/0/page-frame.htmldevtools:https://servicewechat.com/小程序appId/devtools/page-frame.html正式版:https://servicewechat.com/小程序appId/6/page-frame.html三、解决方式。通过nginx做服务器选择。
1、定义一个变量 foo, 配置一个map,把http_referer映射到foo。
map $http_referer $foo {default "prod";~^https://servicewechat.com/[^/]+/0/(.*)$ "dev";~^https://servicewechat.com/[^/]+/devtools/(.*)$ "dev";}2、配置服务器。
upstream dev { server localhost:7777;}upstream prod { server localhost:9999;}3、location 中使用 foo变量, 导航到正确的地址。
这里我用
add_header把foo变量输出一下,作为测试。
location / { #set $foo "$http_referer"; add_header wkfoo 'foo: $foo "$http_referer"'; proxy_pass http://$foo; }4、测试一下。
curl -H 'Cache-Control: no-cache' -I "https://xxx.xxx.com/prod/xxx?参数1=xxx&参数2=xxx" --referer "https://servicewechat.com/xxx/devtools/page-frame.html"curl -H 'Cache-Control: no-cache' -I "https://xxx.xxx.com/prod/xxx?参数1=xxx&参数2=xxx" --referer "https://servicewechat.com/xxx/0/page-frame.html"其他。
实际上这里小程序请求后台的时候,应该加上一个api的版本号。
参考文章:
https://developers.weixin.qq.com/community/develop/article/doc/0004e2dffb0f98852cf7183285b013













