【发布时间】:2018-10-03 01:58:52
【问题描述】:
我最近决定学习 socket.io,以制作实时的东西。我在网站上的“入门”页面之后写了一些东西,并在本地对其进行了测试,直到我让它正常工作为止。
我使用与其他任何内容相同的过程将其上传到我的服务器。我在端口 8002 上运行它,并将它添加到我的反向代理(使用 http-proxy-middleware)下 /pong/*。然后我将/socket.io/* 代理到端口 8002,然后它才起作用。然而,在使用 Firefox 进行检查后,我注意到 socket.io 仅使用轮询作为传输方法,而不是 websockets,经过进一步思考,我决定在其他设备上使用 socket.io 时将/socket.io/* 发送到 8002 并不好未来的项目。
所以我问,如何让多个 socket.io 程序在反向代理后面运行,使用 websockets 作为传输?
proxy.js
const express = require("express")
const fs = require('fs');
const http = require('http');
const https = require('https');
const proxy = require('http-proxy-middleware');
const privateKey = fs.readFileSync('/etc/[path-to- letsencrypt]/privkey.pem', 'utf8');
const certificate = fs.readFileSync('/etc/[path-to-letsencrypt]/cert.pem', 'utf8');
const ca = fs.readFileSync('/[path-to-letsencrypt]/chain.pem', 'utf8');
var credentials = {key: privateKey, cert: certificate, ca: ca};
var app = express();
app.use(function (req, res, next) {
console.log(req.url)
next()
})
app.use("/pong/*", proxy({ target: "http://localhost:8002", pathRewrite: {"^/pong": ""}, ws:true, changeOrigin: true }))
app.use("/pnw/war/*", proxy({ target: "http://localhost:8000" }))
app.use("/pnw/nation/*", proxy({ target: "http://localhost:8001" }))
app.use(express.static("./static"))
https.createServer(credentials, app).listen(443);
// Redirect all HTTP traffic to HTTPS
http.createServer(function (req, res) {
res.writeHead(301, { "Location": "https://" + req.headers['host'] + req.url });
res.end();
}).listen(80);
pong.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http, {
path: "/pong/"
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(8002, function(){
console.log('listening on *:8002');
});
index.html
<script src="/pong/socket.io.js"></script>
<script>
var socket = io({
// transports: ['websocket'], upgrade: false, (using for testing)
path:"/pong"
})
// ...
</script>
我目前所得到的来自于对这个问题的回答: Setting up multiple socket.io/node.js apps on an Apache server?
但是在 Firefox 控制台中,我收到一条警告,内容如下:
Loading failed for the <script> with source “https://curlip.xyz/pong/socket.io.js”,后跟错误io is not defined。在获取 socket.io.js 的网络选项卡中显示 404。
所以我相信正在发生的事情是,因为 express 正在捕获对 / 的请求,所以 socket.io 不能(出于某种原因)服务器 socket.io.js。但是,当我将 / 更改为 /index.html 并加载时,没有任何变化。
【问题讨论】:
标签: node.js socket.io reverse-proxy