Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: client API - io() returns 400 BAD REQUEST when passing window.location #139

Open
sandrina-p opened this issue Dec 23, 2019 · 0 comments

Comments

@sandrina-p
Copy link
Contributor

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.

darrachequesne pushed a commit that referenced this issue Nov 25, 2022
Change `window.location` to `window.location.host`. If
`io(window.location)` is started, it works, but then if we pass
`options`, those are ignored.

Related:

- #139
- #343
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant