Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

前端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
已经折腾好几天了,希望有做过的前辈给予指导,不胜感激


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

另外反向代理少了:

proxy_set_header Connection "Upgrade";

image.png

地址都不一样啊??


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...