-
Notifications
You must be signed in to change notification settings - Fork 877
Open
Description
Problem
On my project, the URL is different based on the env.
Following socketIO Client docs, it says the default value of url
in io(url)
is window.location
. So my code was like this:
// client.js
const url = isDev ? `${window.location.hostname}:5000` : window.location;
socket = io(url, {
query: { playerId },
transports: ['websocket'],
});
// server.js
io.use(function(socket, next) {
console.log('New socket handshake:', socket.handshake);
if (socket.handshake.query && socket.handshake.query.playerId) {
// ...
next()
} else {
return next(new Error('Auth error: missing playerId'));
}
}).on('connection', socket => {
// ....
}
In development this is the log output: (correct)
// log:
{
// .... rest of handshake
url: '/socket.io/?playerId=sandy&EIO=3&transport=websocket',
query: {
playerId: 'sandy',
EIO: '3',
transport: 'websocket'
}
}
But in production env, it doesn't work.
The request returns a 400 BAD REQUEST, ignoring the query passed and it reloads the page.
In my case, the io()
was called on the page load, so this created a constant page refreshing loop.
VM1252:1 GET http://localhost:5000/socket.io/?EIO=3&transport=polling&t=MyoLGr0 net::ERR_ABORTED 400 (Bad Request)
// log:
{
// ....
url: '/socket.io/?EIO=3&transport=polling&t=MyoLGr0t',
query: {
EIO: '3',
transport: 'polling',
t: MyoLGr0
}
Solution
The problem is the incorrect window.location
passed to io()
. It should be window.location.host
.
// client:
const url = isDev ? `${window.location.hostname}:5000` : window.location.host;
socket = io(url, {
query: { playerId },
transports: ['websocket'],
});
I'll open a PR to the docs with this change.
Metadata
Metadata
Assignees
Labels
No labels