[英]How do I use socket.io from a server at a subfolder?
我一直在关注https://www.tutorialspoint.com/socket.io/上的教程,我有以下 2 个文件:
app.js
:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res) {
res.sendFile('index.html', {root: __dirname});
});
io.on('connection', function(socket) {
console.log('A user connected');
//Send a message after a timeout of 4 seconds
setTimeout(function() {
socket.send('Sent a message 4 seconds after connection!');
}, 4000);
socket.on('disconnect', function () {
console.log('A user disconnected');
});
});
http.listen(80, function() {
console.log('listening on *:80');
});
index.html
:
<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
</head>
<script src = "/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('message', function(data){document.write(data)});
</script>
<body>Hello world</body>
</html>
如果我在 Node.js 版本 10.16.3 中运行它并访问http://localhost/
,一切正常。 服务器控制台日志:
A user connected
浏览器最终显示:
Sent a message 4 seconds after connection!
到目前为止,一切都很好!
当我尝试从我的网站运行它时出现问题。 让我们假设它被称为example.com
。 我的 web 托管服务提供商使用相同版本的 Node.js,并进行了设置,以便每个 Node.js 应用程序在子文件夹中运行。 让我们假设它被称为example.com/x
。
访问http://example.com/x
时,浏览器显示:
Cannot GET /x/
所以在app.js
,我改变了这个:
app.get('/', function(req, res) {
res.sendFile('index.html', {root: __dirname});
});
...对此:
app.get('/x', function(req, res) {
// Redirect if no slash at the end
if (!req.url.endsWith('/')) {
res.redirect(301, req.url + '/')
}
res.sendFile('index.html', {root: __dirname});
});
现在初始页面加载,但浏览器控制台记录:
The resource from “http://example.com/socket.io/socket.io.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).
Loading failed for the <script> with source “http://example.com/socket.io/socket.io.js”.
ReferenceError: io is not defined
显然,我的应用程序没有机会处理此请求,因为它是针对主域的。
所以我更改了两个文件:在app.js
中,我更改了这一行:
var io = require('socket.io')(http);
对此:
var io = require('socket.io')(http, {path: "/x/socket.io"});
在index.html
中,我更改了这一行:
<script src = "/socket.io/socket.io.js"></script>
对此:
<script src = "/x/socket.io/socket.io.js"></script>
这消除了浏览器控制台中的错误,但它似乎仍然没有连接。
浏览器从不显示:
Sent a message 4 seconds after connection!
当我在http://localhost/x/
中运行所有这些时也是如此,并且 Node.js 控制台从不记录:
A user connected
有没有比我迄今为止所做的更改更简单的方法来解决所有这些问题? 如果没有,我还需要做什么才能使其正常工作?
还剩一步。
在index.html
中,更改此行:
var socket = io();
...对此:
var socket = io.connect("/", {path: "/x/socket.io"});
这应该适用于http://example.com/x
和http://localhost/x
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.