node.js 如何解决 Socket.io 404(未找到)错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27393705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to resolve a Socket.io 404 (Not Found) error?
提问by Zee
I am using Socket.io with Express. In my project I have a login page and a home page. When I do successful login, I navigate to localhost:3000/home where I get this error:
我正在将 Socket.io 与 Express 一起使用。在我的项目中,我有一个登录页面和一个主页。当我成功登录时,我导航到 localhost:3000/home 出现此错误:
GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=1418187395022-0 404 (Not Found)
I did not do any modification in my app.js(project created by express ).
我没有对我的app.js(由 express 创建的项目)进行任何修改。
index.js:
索引.js:
var express = require('express');
var router = express.Router();
var http = require('http');
var fs = require('fs');
var io = require('socket.io')(http);
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
router.get('/home', function(req, res) {
res.render('home', { title: 'Express' });
});
io.on('connection', function(socket){
console.log("User Connected");
socket.on('chat message', function(msg){
io.emit('chat message', msg);
console.log("Message");
});
socket.on('disconnect', function(msg){
console.log("User DisConnected");
});
});
router.post('/authenticate', function(req, res) {
fs.readFile("./public/Verification/Users.json", "utf8", function (err, data) {
if (err)
console.log(err);
else{
var result = JSON.parse(data);
for(var i=0;i<result.Users.length;i++){
if(req.body.username == result.Users[i].username && req.body.password == result.Users[i].password){
console.log("Success!!!!!!!!!!!!!!");
res.location("home");
res.redirect("home");
}
}
}
});
});
module.exports = router;
In my layout.jadeI defined Socket.io like this:
在我的layout.jadeSocket.io 中,我是这样定义的:
script(src='https://cdn.socket.io/socket.io-1.2.0.js')
回答by jfriend00
If you're running Express 4, it appears to me like you're missing the lines of code:
如果您正在运行 Express 4,在我看来,您似乎缺少以下代码行:
var app = express();
var server = app.listen(3000);
That will start your web server and set it to port 3000. See the bone simple Express 4 app here: http://expressjs.com/4x/api.html
这将启动您的 Web 服务器并将其设置为端口 3000。请在此处查看简单的 Express 4 应用程序:http: //expressjs.com/4x/api.html
And, then to start up socket.io, you would add:
然后,要启动 socket.io,您需要添加:
var io = require('socket.io').listen(server);
And, there is no need for this line:
而且,不需要这一行:
var http = require('http');
回答by Kalle H. V?ravas
Since I was battling with this issue for the past 5 hours. And this is the first result in google.
因为我在过去的 5 个小时里一直在与这个问题作斗争。这是谷歌的第一个结果。
Of course its 2015 and some of the code has changed.
当然它的 2015 和一些代码已经改变了。
I think currently the best start of the index.js code is:
我认为目前 index.js 代码最好的开始是:
var express = require('express'),
http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(3000);
The order is highly important.
顺序非常重要。
My problem was, that everything was installed properly and node was listening. However the example.com/socket.io/socket.io.js and example.com/socket.io/?eio=... was 404 not found. However, when I tried example.com:3000/socket.io/socket.io.js everything worked. So now was the question, how to change the getJSON query to have the port part.
我的问题是,一切都安装正确并且节点正在监听。但是 example.com/socket.io/socket.io.js 和 example.com/socket.io/?eio=... 是 404 未找到。但是,当我尝试 example.com:3000/socket.io/socket.io.js 时,一切正常。所以现在的问题是,如何更改 getJSON 查询以包含端口部分。
So the solution was to edit the main.js, that is being added to the index.html, where your chat is. There is:
所以解决方案是编辑 main.js,它被添加到 index.html,你的聊天所在的位置。有:
var socket = io();
to be replaced with
替换为
var socket = io.connect('http://example.com:3080');
This corrects the getJSON queries URL and adds the correct port and no more 404. I hope it helps someone in the future.
这会更正 getJSON 查询 URL 并添加正确的端口,而不再是 404。我希望它可以帮助将来的某个人。
回答by IAMSTR
Please change your config to this
请将您的配置更改为此
var express = require('express');
// App setup
var app = express();
var socket = require('socket.io')
var server = app.listen(4000, function(){
console.log('listening for requests on port 4000,');
});
let io = socket(server)
io.on('connection', function(socket){
console.log(`${socket.id} is connected`);
});
回答by melshor essomassor
This is how i solve it on server side (2018):
这就是我在服务器端(2018)解决它的方法:
const app = express();
const socketIO = require('socket.io');
const server = express()
.use(app)
.listen(PORT, () => console.log(`Listening Socket on ${ PORT }`));
const io = socketIO(server);
On client side
在客户端
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.1/socket.io.js"></script>
It looks easy but I spent hours before I found the solution since the solutions above didn't work for me.
看起来很简单,但我花了几个小时才找到解决方案,因为上述解决方案对我不起作用。
回答by Subhash
just call the listen of the server and with the callback I passed the server instance to module.
只需调用服务器的监听并通过回调将服务器实例传递给模块。
part of the bin/wwwfile from express app
bin/www来自 express 应用程序的文件的一部分
var server = http.createServer(app);
server.listen(port, function () {
console.log('app listening on *:' + port);
require('../socket')(server);
console.log('socket server will be on *:' + port);
});
server.on('error', onError);
server.on('listening', onListening);
and this is how my socket module socket.js
这就是我的套接字模块 socket.js
var io = {};
module.exports = (server, serveradmin) => {
io = require('socket.io')(server);
io.on('connection', function (socket) {
console.log(socket + ' a user connected');
});
}
all of the socket listeners and emits managing from here.
所有套接字侦听器并从这里发出管理。
回答by Burrito
For anyone doing this with nginx proxying to node.js, the problem might be the nginx conf instead of the node.js code.
对于使用 nginx 代理到 node.js 的任何人来说,问题可能是 nginx conf 而不是 node.js 代码。
You can test with a GET request (use curl, Postman, or browser) to http://localhost/socket.io/(with the trailing slash) and one to http://localhost:3000/socket.io/
您可以使用 GET 请求(使用 curl、Postman 或浏览器)测试http://localhost/socket.io/(带有尾部斜杠)和一个到http://localhost:3000/socket.io/
If http://localhost/socket.io/gives 404 not found or "Cannot GET /", but http://localhost:3000/socket.io/returns a response like:
如果http://localhost/socket.io/给出 404 not found 或“Cannot GET /”,但http://localhost:3000/socket.io/返回如下响应:
{"code":0,"message":"Transport unknown"}
Then the backend node.js and socket.io are working, but nginx is not passing the request correctly.
然后后端 node.js 和 socket.io 正在工作,但 nginx 没有正确传递请求。
Check it should look something like:
检查它应该看起来像:
location /socket.io/ {
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_pass http://127.0.0.1:3000;
}
In particular, note there is no trailing slash at the end of proxy_pass http://127.0.0.1:3000, since we want to pass the original request URI as is (i.e. including /socket.io).
特别要注意,在 末尾没有斜杠proxy_pass http://127.0.0.1:3000,因为我们希望按原样传递原始请求 URI(即包括 /socket.io)。
From the nginx proxy_pass docs:
If the proxy_pass directive is specified with a URI, then when a request is passed to the server, the part of a normalized request URI matching the location is replaced by a URI specified in the directive:
location /name/ { proxy_pass http://127.0.0.1/remote/; }If proxy_pass is specified without a URI, the request URI is passed to the server in the same form as sent by a client when the original request is processed, or the full normalized request URI is passed when processing the changed URI:
location /some/path/ { proxy_pass http://127.0.0.1; }
如果 proxy_pass 指令使用 URI 指定,那么当请求传递到服务器时,与位置匹配的规范化请求 URI 部分将被指令中指定的 URI 替换:
location /name/ { proxy_pass http://127.0.0.1/remote/; }如果proxy_pass 没有指定URI,则请求URI 以与客户端在处理原始请求时发送的相同形式传递给服务器,或者在处理更改的URI 时传递完整的规范化请求URI:
location /some/path/ { proxy_pass http://127.0.0.1; }
The header requirements are covered at https://www.nginx.com/blog/nginx-nodejs-websockets-socketio/(essentially websocket requires the Upgrade header which requires HTTP/1.1)
https://www.nginx.com/blog/nginx-nodejs-websockets-socketio/涵盖了标头要求(本质上,websocket 需要升级标头,它需要 HTTP/1.1)

