I'm trying to set a http header when socket.io client makes the connection request. Is there a way to do this?
Here is what i'm doing:
// server side var io = socketio(server); io.use(function (socket, next) { // authorize using authorization header in socket.request.headers }); // client side var socket = io(); // i'm trying to set an authorization header in this http reqeust
Any ideas? Thanks.
Although Socket.IO indeed uses WebSocket for transport when possible, it adds additional metadata to each packet. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a plain WebSocket server either.
The error is simple to fix. Add cors and the origin that can communicate with the server, and that's all! const io = require('socket.io')(server, {cors: {origin: "*"}}); In the code above, I added a wildcard as my origin because I would like any origin to access it.
You can check the socket. connected property: var socket = io. connect(); console.
listen(port); // Create a Socket.IO instance, passing it our server var socket = io. listen(server); // Add a connect listener socket. on('connection', function(client){ console. log('Connection to client established'); // Success!
You can use extraHeaders
option, if you are using socket.io-client >= 1.4.
For example:
var socket = io("http://localhost", { extraHeaders: { Authorization: "Bearer authorization_token_here" } });
engine.io-client, which is a backend of socket.io-client, introduced extraHeaders
support on 2015-11-28.
It seems like the client doesn't support setting headers, as not all transports allow for the setting of headers.
This post by facundoolano details a workaround to authentication that doesn't require placing the auth token in the query string.
His workaround module can be found at https://github.com/invisiblejs/socketio-auth.
Makes me wonder why on server-side, socket.io allows for the request headers to be accessed...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With