ZBLOG

vue 前端页面发送websocket请求,wss,nginx该如何配置

  1. 安装 nginx 首先需要安装 nginx,可以根据官网提供的安装教程进行安装:https://nginx.org/en/docs/install.html

  2. 配置 nginx 在 nginx 的配置文件中添加以下内容:

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://localhost:8080;  # 前端页面所在的地址
        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_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    location /ws/ {  # websocket 请求所在的地址
        proxy_pass http://localhost:3000;  # 后端 websocket 服务所在的地址
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
    }
}

这里假设前端页面所在的地址是 http://localhost:8080,后端 websocket 服务所在的地址是 http://localhost:3000。其中,location / 表示普通 HTTP 请求,location /ws/ 表示 WebSocket 请求。

  1. 启动 nginx 启动 nginx 服务:
sudo systemctl start nginx
  1. 配置 SSL/TLS 如果希望使用 HTTPS 进行通信,则需要为 nginx 配置 SSL/TLS。可以参考官方文档进行配置:https://nginx.org/en/docs/http/configuring_https_servers.html

在 SSL/TLS 配置完成后,需要将前端页面的请求地址和后端 websocket 服务的地址改为 https 协议,即:

let ws = new WebSocket('wss://example.com/ws/');
axios.get('https://example.com/api/xxx');

以上是基本的 nginx 配置方式,具体的配置还要根据实际情况进行调整。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=1177

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?