这个问题是我的项目中用到websokect,在本地是正常连接,但是放到线上,就连接不上,然后哦我经过一晚的摸索,终于发现问题产生的原因,和解决办法,记录下!
服务器:阿里云服务器
后端:node.js(koa2)Ï
前端:react
本地环境
NODE_ENV = 'development'
本地环境接口地址
VITE_API_URL = 'http://localhost:8000/'
本地环境ws地址
VITE_WS_URL = 'ws://localhost:8000/'
线上配置
线上环境
NODE_ENV = 'production'
线上环境接口地址
VITE_API_URL = 'baidu.com/' (模拟)
线上环境ws地址
VITE_WS_URL = 'wss://baidu.com/' (模拟)
这是代码上的本地环境和线上环境的配置,项目部署上线后,在连接websoket时,发现连接不是上,出现一下报错,
PieChart-d56bcce4.js:19 WebSocket connection to 'wss://baidu.com/' failed:
因为线上接口时在服务器上运行的,通过nginx代理过来的,检查nginx配置,如下
server {
#配置HTTPS的默认访问端口为443。
#如果未在此处配置HTTPS的默认访问端口,可能会造成Nginx无法启动。
#如果您使用Nginx 1.15.0及以上版本,请使用listen 443 ssl代替listen 443和ssl on。
listen 443 ssl;
#填写证书绑定的域名
server_name baidu.com;
root html;
index index.html index.htm;
#填写证书文件名称
ssl_certificate cert/baidu.com.pem;
#填写证书私钥文件名称
ssl_certificate_key cert/baidu.com.key;
ssl_session_timeout 5m;
#表示使用的加密套件的类型
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
#表示使用的TLS协议的类型,您需要自行评估是否配置TLSv1.1协议。
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
location / {
#Web网站程序存放目录
# root html;
# index index.html index.htm;
proxy_pass http://baidu.com:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_ssl_protocols TLSv1.2 TLSv1.3;
}
经过我的摸索后,问题产生的原因是,服务端没有接受到前端的连接,导致无法正常通信 解决办法:nginx需要配置对websoket的连接配置,指向线上地址代理的ssl地址,配置如下:
location /ws/ {
proxy_pass http://baidu.com:8000; #通过配置端口指向部署websocker的项目
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
}
这样配置后,前端线上连接的websokect地址 应为 wss://baidu.com/ws/ ,这样就可以正常通信了!!