Socket.IO Getting 404 Errors on Some URLs, but not others

by bobmartin1234   Last Updated August 13, 2019 19:26 PM

I am trying to use Socket.IO in my web application and it has worked great so far. However, I have been trying to fix one specific issue for a long time and have not been able to find anyone else having the same issue. Socket.IO works great on URLs where it is just site.com/example, however, when I stack paths on the domain, I get a 404 in socket.IO. For example, site.com/user/example displays a 404 for socket.IO. In the log, it tries to access socket.IO at site.com/user/socket.io/... when it needs to access it at site.com/socket.io. It seems to only replace the url after the last / so site.com/ex/a would make it try to get socket.io at site.come/ex/socket.io.(I am using ExpressJS, I didn't know if that was relevant.)

I have tried to set the path and resource for socket.io to use in the client script. Also, I included the path when binding the socket.io instance to the http server.

Here is my server side code.

var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server, {path: '/socket.io'});

Here is my client side code.

var socket = io.connect('https://example.net', {
    path: '/socket.io',
    resource: '/socket.io',
    transports: ['websocket'],
    upgrade: false
})

Thanks so much for all help! (I am sorry for any incorrect formatting of this question, this is my fist time asking on StackOverflow!)



Answers 1


You likely need a leading slash on the socket.io script tag.

The big clue is when you said your socket.io script loads when the page URL is https://example.net/dashboard, but doesn't load when it's https://example.net/user/fludo. The problem is that your <script> tag is using a page relative link with no leading / on the URL. That means the browser will combine the path of the page URL with the filename in your <script> tag. But, you don't want to use the path of the page. You want to load it from the same place every time. So, to do that, you change from this:

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

to this:

<script src="/socket.io/socket.io.js"></script>
jfriend00
jfriend00
August 13, 2019 19:25 PM

Related Questions


Updated May 31, 2015 03:11 AM

Updated June 14, 2017 02:26 AM

Updated October 13, 2017 19:26 PM

Updated December 15, 2017 04:26 AM