尚未加载Socket.io.js

时间:2018-12-19 13:42:53

标签: javascript node.js sockets websocket socket.io

我正在使用node.js和express.js,并且试图将socket.io添加到我的一个.ejs文件中,但是当我这样做时,出现了一些奇怪的错误:

 Failed to load resource: the server responded with a status of 404 (Not Found)                socket.io/?EIO=3&transport=polling&t=MV6f2K2
 Failed to load resource: the server responded with a status of 404 (Not Found)                                     socket.io/?EIO=3&transport=polling&t=MV6f2cR

然后每秒:

 GET https://www.mywebsite.eu/socket.io/?EIO=3&transport=polling&t=MV6f2cR 404 (Not Found)                   socket.io.js:7

有我的文件: app.js:

    const fs = require('fs');
    const express = require('express');
    const app = express();
    const http = require('http').Server(app);
    const fileUpload = require('express-fileupload');
    var io = require('socket.io')(http);
    .....
    var router = express.Router();
    var pathView = __dirname + "/views/";
    app.use(express.urlencoded({extended: true}));
    app.use(express.json());
    const listenPort = 8000;
    app.set('view engine', 'ejs');
    app.use(express.static('public'));
    app.use('/public', express.static('public'));
    app.use('/scripts', express.static(__dirname + '/node_modules/'));
    //SOCKET IO PART

    io.on('connection', function(socket){
    console.log('a user connected');
    });

   //SOCKET IO PART

   ..........
   app.get & app.post requests
   ..........

   app.use( "/", router);

   // Not found
   app.use("*",function(req,res){
   res.setHeader('Content-Type', 'text/html');
   res.status(404).send('Page introuvable !');
   });

   // Run server
   app.listen(listenPort, function () {
   console.log('Example app listening on port ' + listenPort )
   })

profile.ejs:

   .....content of the page(it's working well).......
   <%- include('scripts') -%>
   <script src="/scripts/socket.io/socket.io.js"></script>

   </html>

   <script>

   var socket = io();

   </script>

我不得不提到我是从socket.io-client复制了socket.io.js的,如果不这样做,我会将其放入socket.io中,那我会在devtools中遇到404文件丢失的错误。

希望不需要其余代码,我没有添加它,因为它很多,而且与socket.io无关。

1 个答案:

答案 0 :(得分:1)

我认为您应该尝试将其分解以找出您的问题。显然您没有到达插座。

尝试拥有这样的服务器:

if [ git merge-base --is-ancestor source destination ] ...

和客户:

var express         = require('express')
var app             = express()
var server          = require('http').Server(app)
var io              = require('socket.io')(server)

io.on('connection', function(socket) {  
    console.log('Socket did connect');
});

server.listen(8080)

如果这行得通,那就应该添加其余的代码。 Ejs不会成为问题,因为它在投放之前已被编译为常规HTML。 问题是,如果您的客户端在与服务器不同的域(或端口)上运行。如果是这样,则必须在客户端站点的io()内部定义它,例如:var socket = io();