目录 一、问题 1.1 问题描述 1.2 问题详细描述 二、解决 2.1 https下的链接类型 2.2 修改Nginx的配置 一、问题 1.1 问题描述 一个小项目中使用到了websocket,这个WEBSocket在本地完全是完全正常
目录
一个小项目中使用到了websocket,这个WEBSocket在本地完全是完全正常运行的,不管是前后台的信息通讯 还是 异常报错接收,无任何异常,但当把后台代码部署到阿里云服务器后,websocket就再也链接不上了;
(PS: 博主的websocket是应用在uni-app中的,因此使用的是uni-app自带的websocket,这个本质上没有任何区别~)
uni-app端的简易websocket代码,大致如下;
// 建立websocketuni.connectSocket({ url: Setting.wsUrl});// 打开uni.onSocketOpen(res => { console.log('--- 数据通信已打开 ---');});uni.onSocketError((res) => { console.log('--- 数据通信连接失败,请检查 ---');});uni.onSocketMessage((res) => { // console.log('收到服务器内容:' + res.data); this.resultData(JSON.parse(res.data))});
当项目启动打开websocket页面,与后台链接成功后前台会打印出:--- 数据通信已打开 ---,
运行后在本地正确打印了结果;
但是 当后台文件打包部署到阿里云服务器 后,websocket链接异常,无法正确打印结果;
我在这里一共遇到了 两个错误,第一个分别是 https下的链接类型 以及 nginx配置异常 这两个问题,这两个问题解决后,websocket即可正常使用了;
这个问题主要在于链接中的类型写错了,需要把 ws 改写成 wss ,如本地的时候由于使用的是Http类型,因此websocket的链接写成了
ws://localhost:5002
但当部署到服务器之后,由于服务器是https的格式,因此ws显然不再合适了,需要改成 wss,即
wss://www.xxxxxx.com/xxx/
放到具体uni-app代码中就是这样
// 建立websocketuni.connectSocket({ url: "ws://localhost:5002"});// 需要改成 wss 开头的uni.connectSocket({ url: "wss://www.xxxx.com/xxxx"});
这样,就将兼容https下的websocket了;
除了改wss外,nginx同样要修改,默认情况下的Nginx是不支持的,因此需要手动去开通这个功能;
首先,找到Nginx的配置文件,然后在配置文件中为需要开通websocket的后台加上这几条语句
proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Real-IP $remote_addr;
以我这边为例,改之前是这样的
server {listen 443 ssl;server_name www.xxxx.com;# access_log /var/log/nginx/access.log main;# error_log /var/log/nginx/error.log;ssl_certificate #填写解压的pem文件ssl_certificate_key #填写解压的key文件# ssl on;ssl_session_cache shared:SSL:10m;ssl_session_timeout 50m;ssl_ciphers HIGH:!aNULL:!MD5;ssl_prefer_server_ciphers on;location / {root 前台文件;}location /api/ {proxy_pass 后台接口地址;}location /api2/ {proxy_pass 后台接口地址; }}
改完之后如下
server {listen 443 ssl;server_name www.xxxx.com;# access_log /var/log/nginx/access.log main;# error_log /var/log/nginx/error.log;ssl_certificate #填写解压的pem文件ssl_certificate_key #填写解压的key文件# ssl on;ssl_session_cache shared:SSL:10m;ssl_session_timeout 50m;ssl_ciphers HIGH:!aNULL:!MD5;ssl_prefer_server_ciphers on;location / {root 前台文件;}location /api/ {proxy_pass 后台接口地址;}location /api2/ {proxy_pass 后台接口地址;proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Real-IP $remote_addr; }}
加上之后 重启Nginx,websocket即可正常使用了,解决问题;
来源地址:https://blog.csdn.net/zy21131437/article/details/130913185
--结束END--
本文标题: 解决websocket在部署到服务器https下无法使用的问题
本文链接: https://www.lsjlt.com/news/400465.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-13
2024-05-13
2024-05-11
2024-05-11
2024-05-10
2024-05-07
2024-04-30
2024-04-30
2024-04-30
2024-04-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0