我在 ubuntu 上使用 MERN 部署了 socket.io 项目。 但服务器无法与客户端连接 原因似乎是nginx位置设置有问题。 环境: ubuntu nginx 下午2
这是客户端
//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
我解决了 客户端无法与服务器连接的原因是使用 //REACT_APP_API_URL = 'http://192.168.109.33:4000/api'; 这里我删除了 api 前缀。 现在效果很好。
我正在使用nextjs,我也有同样的问题。你能告诉我我们如何需要在客户端连接时添加 API_URL 吗?在我使用 nextjs 的情况下,我也需要添加它吗? 谢谢