我是webdev的新手,我正在尝试用proxy_pass在nginx上部署一个express应用程序!
这个应用程序在我的机器上运行得很好,但是当我从nginx尝试时出现了连接错误。
下面是我的nginx配置:
http {
include mime.types;
server {
listen 80;
root /var/www/sites;
location /someapp/ {
proxy_pass http://localhost:9999/;
}
location /someOtherApp/ {
proxy_pass http://localhost:5173/;
}
location /theAppWithSocketIo/socket.io/ {
proxy_http_version 1.1;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy false;
proxy_pass http://localhost:3000/socket.io/;
proxy_redirect off;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location /theAppWithSocketIo/ {
proxy_pass http://localhost:3000/;
}
}
}
客户代码:
"use strict";
var Socket = io(
'http://<IPADRESS>',
{
path: '/<APPPATH>',
rejectUnauthorized: false,
extraHeaders: {
token: document.cookie.split( "=" )[ 1 ]
}
}
);
Socket.on("connect_error", (err) => {
console.log(`connect_error due to ${err}`);
});
服务器代码:
const express = require("express");
const path = require("path");
const { createServer } = require("http");
const { Server } = require("socket.io");
const connectDB = require("./db");
const cors = require('cors');
const cookieParser = require("cookie-parser");
// Create Express Socket.io server
const app = express();
const whitelist = [<URLS>];
const corsOptions = {
origin: (origin, callback) => {
if (origin === undefined || whitelist.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
credentials: true
};
app.use(cors(corsOptions));
const httpServer = createServer(app);
const io = new Server(httpServer);
connectDB();
io.on("connection", socket => console.log('connected'));
app.use(express.json({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '/')));
// Other Routes
const PORT = 3000; // config.get('PORT')
const listener = httpServer.listen(PORT, () => {
console.log("Node.js listening on port " + listener.address().port);
});
客户端socket.io无法连接到服务器,我从Socket.on('connect_error')获得多个控制台日志,但它们对我帮助不大..// connect_error due to Error:伺服器错误
我查了一下https://socket.io/docs/v3/troubleshooting-connection-issues/我的ws请求是200,但他们从来没有到达服务器。在io.on('连接')的console.log从来没有得到调用。
任何帮助都是受欢迎的..我已经在这上面两天了..
1条答案
按热度按时间ibps3vxo1#
服务器和ws不能在同一端口上运行!
当一些新手尝试时,如果有一个错误就好了。