简体   繁体   中英

POST http://localhost:3000/socket.io/?EIO=3&transport=polling&t=NQUneY3 400 (Bad Request) in ejs and nodejs

I am very new to this socket.io.

I have the code this is a node server code:

var express = require("express");
var app = express();
var http = require("http").createServer(app);
var socketIO = require("socket.io")(http);
var socketID = "";

socketIO.on("connection", function (socket) {
  console.log("User is conneected ", socket.id);
  socketID = socket.id;
});

And here is the code for a ejs file:

......

<script src="/public/js/socket.io.js"></script>

<script>
......
var socketIO = io("http://localhost:3000");
......
</script>
...... 

And the socket.io.js file is here :

I tried but nothing is working. The same error pops whenever I refresh the page. I am very new to this and I really want to get it sorted as soon as possible!!

I already have a listen function just after socket.on :

http.listen(3000, function () {
  console.log("Server has started running!!");
  .........................
.............
})

The below code is working for me.

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

io.sockets.on('connection', function (socket) {
        console.log(socket);
})

server.listen(3000, function(){
    console.log('listening on *:3000');
});

<script src="/socket.io/socket.io.js" > </script>

<script>
    $(function () {
        var socket = io.connect();
    });
</script>

socket.io.js that you have mentioned is the same as that from the https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js.. . check the installed version of serail io in package.json and place the same version here in the path socket.io/2.2.0 it will work

Please Check versions of socket.io in your Frontend and Backend. It should be compatible. I had same issue so I solved it with version change. Like I had 2.2.0 in my frontend so I install 1.7.2 in backend or same as frontend.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM