vue 项目如何用nginx反向代理WebSocket请求地址 您所在的位置:网站首页 nginx配置websocker连接 vue 项目如何用nginx反向代理WebSocket请求地址

vue 项目如何用nginx反向代理WebSocket请求地址

2023-07-17 09:14| 来源: 网络整理| 查看: 265

原因

在VUE项目中使用WebSocket时,是将IP与端口进行固定,但是当环境地址发生变更时,就需要在代码中进行修改,并重新打包发布版本,很是麻烦,当然这样也是不可取的。因此使用nginx反向代理WebSocket就可以解决这个问题。

VUE项目代码片段 export default { data(){ return { webSocket: null } }, mounted(){ this.initWebSocket(); }, methods:{ initWebSocket(){ let vm = this; let wsServer = `${location.protocol === 'https' ? 'wss' : 'ws'}://${location.host}/websocket`; vm.webSocket = new WebSocket(wsServer); vm.webSocket.onopen = function(event) { }; vm.webSocket.onmessage = function(msg) { }; vm.webSocket.onClose = function(msg) { }; vm.webSocket.onError = function(err) { } } } } nginx文件配置 events { worker_connections 1024; ## Default: 1024 } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 9001; server_name localhost; location / { root D:/code/ai-village-html/dist/; index index.html index.htm; } #nginx配置websocket location ^~ /websocket { proxy_pass http://192.168.1.11:8088; #websocket地址 proxy_http_version 1.1; 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_read_timeout 120s; proxy_set_header Upgrade websocket; proxy_set_header Connection Upgrade; } location ^~/proxy{ rewrite ^/proxy/(.*)$ /$1 break; #代理字符串 proxy_pass http://192.168.1.11:8088; #需要代理的地址 } } }

这样就可以方便、快捷实现在发生环境改变不改动代码的情况下对WebSocket请求进行配置!



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有