微信小程序需要使用https與wss能才進行連接,雖然開發(fā)模式下可以使用http與ws,但發(fā)布的時候還是需要安全協(xié)議,網(wǎng)上的各種配置是超多超復雜的,這里已經(jīng)對nginx指定版本進行最簡單的配置,可用。
使用教程
nginx版本
-
$ nginx -v
-
nginx version: nginx/1.12.2
系統(tǒng)Centos7
-
$ uname -r
-
4.14.11-1.el7.elrepo.x86_64
cat /etc/nginx/conf.d/test.conf
-
server {
-
listen 80;
-
server_name test.dounine.com;
-
return 301 https://$host$request_uri;
-
}
-
-
server {
-
listen 443;
-
server_name test.dounine.com;
-
ssl on;
-
ssl_certificate /etc/nginx/ssls/test.xxxx.pem;
-
ssl_certificate_key /etc/nginx/ssls/test.xxxx.key;
-
-
location / {
-
client_max_body_size 100m;
-
proxy_pass http://localhost:7777;
-
proxy_set_header Host $host;
-
proxy_set_header X-Real-IP $remote_addr;
-
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
-
proxy_set_header Upgrade $http_upgrade;
-
proxy_set_header Connection "Upgrade";
-
}
-
-
}
微信小程序代碼
-
wx.connectSocket({
-
url: 'wss://test.dounine.com/ws'
-
});
-
wx.onSocketOpen(function(res) {
-
console.info('websocket連接成功');
-
});
-
wx.onSocketClose(function(res) {
-
console.log('WebSocket 已關(guān)閉!')
-
});
-
wx.onSocketError(function(res){
-
console.log('WebSocket連接打開失敗,請檢查!')
-
});
-
wx.onSocketMessage(function(res) {
-
console.log('收到服務(wù)器內(nèi)容:' + res.data)
-
})
|