如何在nginx配置中设置套接字io位置

4dc9hkyq  于 2022-11-21  发布在  Nginx
关注(0)|答案(1)|浏览(135)

我socket.io在ubuntu上使用MERN部署了www.example.com项目。但服务器无法与客户端连接,原因似乎是nginx位置设置有问题。环境:ubuntu nginx pm2语言
这是客户端

//REACT_APP_API_URL = 'http://192.168.109.33:4000/api';
var connectionOptions = {
  path:'/socket.io',
};

const socket = socketIOClient(process.env.REACT_APP_API_URL,connectionOptions);

这是服务器端代码

const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);
const bodyParser = require("body-parser");
const socketIo = require("socket.io");
const cors = require("cors");
const PORT = 4000;

app.use(bodyParser.json({ limit: "10mb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "10mb", extended: true }));
app.use(cors({ origin: true }));

console.log("visited");

server.listen(PORT, function () {
  console.log("Server is running on Port: " + PORT);
});

let io = socketIo(server, {
  path:'/socket.io',
  cors: {
      origin: "http://servemirates.com",
      methods: ["GET", "POST"],
      transports: ["polling"],
      credentials: true
  },
  allowEIO4: true
});

io.on("connection", (socket) => {
  console.log("New client connected");
  socket.io = io;
});

nginx配置

upstream loadbalancer {
    least_conn;
    server localhost:4000 max_fails=3 fail_timeout=30s;
    keepalive 8;
}

server {
    index index.html index.html;
    server_name 35.168.132.12;
    location / {
        root /var/www/MernStack-rota/frontend/build/;   
        try_files $uri $uri/ /index.html;
    }
    location /api/ {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host $http_host;
        add_header Cache-Control "no-cache, private, no-store, must-revalidate, max-stale=0";
        proxy_pass http://localhost:4000/;
        proxy_buffering on;
    }
    location /socket.io/ {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_pass http://localhost:4000/socket.io/;
    }
    location ~ /\.(?!well-known).*{
        deny all;
    }
}

控制台输出

visited
Server is running on Port:4000

io.connection函数似乎无法运行
我想要的结果是

visited
server is running on Port:4000
New client connected
6ss1mwsb

6ss1mwsb1#

解决了客户端无法连接服务器的原因是使用了//REACT_APP_API_URL = 'http://192.168.109.33:4000/api';这里我去掉了api前缀。现在它工作得很好。

相关问题