前端react后端express用了socket.io怎么设置nginx反代?

前后端分离,部署在同一服务器的两个端口
前端80 后端4000 我的服务器ip地址是49.232.150.231
在大佬们的建议和自己的理解下修改之后的状况如下,但是错误依然存在,望路过的大佬再次指点迷津

前端react socket代码

function initIO(dispatch, userid) {
    if(!io.socket) {
       io.socket = io('ws://49.232.150.231:80')  
      io.socket.on('receiveMsg', function (chatMsg) {
        if(userid===chatMsg.from || userid===chatMsg.to) {
          dispatch(receiveMsg(chatMsg, userid))
        }
      })
  
    }
  }

后端express socket代码

const {Chat} = require('../model/chat')
module.exports = function (server) {
  const io = require('socket.io')(server)

  // 监视客户端与服务器的连接
  io.on('connection', async function (socket) {
    console.log('有一个客户端连接上了服务器')

    // 绑定监听, 接收客户端发送的消息
    socket.on('sendMsg', async function ({from, to, content}) {
      // 处理数据(保存消息)
      const chat_id = [from, to].sort().join('_')// from_to或者to_from
      const create_time = Date.now()
      var chatMsg = await Chat.create({from,to,content,chat_id,create_time})
      io.emit('receiveMsg', chatMsg)
    })
  })

}

express端口的监听我是在bin文件夹下的www文件中,不是在socket文件中这样不知道会不会有问题

var port = normalizePort(process.env.PORT || '4000');
app.set('port', port);
var server = http.createServer(app);
server.listen(port);

目前的nginx反代设置如下

server 
{ 
  listen 80;
  server_name localhost; 
    
location /{
        root /www/wwwroot/react.com;
    }         
    
location  /api/ {
      proxy_pass http://localhost:4000/; 
} 

location /socket.io {
         proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_pass http://127.0.0.1:4000;
    }
    

}

静态资源请求都正常 只有socketio那一块有问题
可以收发消息但是是通过ajax轮询
websocket没有实现
报错图片如下:
image.png
已经折腾好几天了,希望有做过的前辈给予指导,不胜感激

阅读 474
评论
    3 个回答

    我看你前端连的地址是 ws://49.232.150.231:4000 啊,可从你的 nginx 配置上来看,4000 端口应该是没开放的,而是通过 /socket.io/ 路径转发,那你前端得连这个反向代理的地址啊。

    另外反向代理少了:

    proxy_set_header Connection "Upgrade";

    image.png

    地址都不一样啊??

      proxy_pass的结尾不要/

          location /socket.io {
              proxy_set_header Upgrade $http_upgrade;
              proxy_set_header Connection "upgrade";
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_pass http://127.0.0.1:4000;
          }

        自己解决 玄学,在各种百度google加东西,最后我都不知道是加的哪一条语句不再报错了的,惭愧
        遂把整个nginx.conf的配置放出来
        以及测试了设置socket.io的时候加不加反斜杠/都可 只要 proxy_pass http://127.0.0.1:4000;4000后面不加反斜杠/就行(真的玄学,其实还是自己学艺不精暂时还不知道原理)

        user  root;  
        worker_processes  auto;
        
        events {
            worker_connections  1024;
        }
        
        
        http {
            include       mime.types;
            default_type  application/octet-stream;
        
            sendfile        on;
            #tcp_nopush     on;  
        
            #keepalive_timeout  0;  
            keepalive_timeout  65;
          
          # http_proxy 设置
            client_max_body_size   10m;
            client_body_buffer_size   128k;
            proxy_connect_timeout   75;
            proxy_send_timeout   75;
            proxy_read_timeout   75;
            proxy_buffer_size   4k;
            proxy_buffers   4 32k;
            proxy_busy_buffers_size   64k;
            proxy_temp_file_write_size  64k;
         
        
           server 
        { 
          listen 80;
          server_name localhost; 
            
        location /{
                root /www/wwwroot/react.com;
            }         
            
        location  /api/ {
              proxy_pass http://localhost:4000/; 
        } 
        location /socket.io {
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_pass http://127.0.0.1:4000;
            }
        
          }
        }
        
          撰写回答

          登录后参与交流、获取后续更新提醒

          相似问题
          推荐文章