socketio / socketio/socket.io-website
Bug: client API - io() returns 400 BAD REQUEST when passing `window.location`
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 342
- Forks
- 1.1k
- PR merge metrics
- No merged PRs in 30d
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.
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start from the Socket.IO client API documentation and the client.js example described in the issue. Update the documented URL example to use window.location.host rather than window.location, then verify that the example preserves the query parameters and avoids the reported 400 response.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, nodejs
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 1/5
- Estimated time
- Under an hour
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 55/100