I try to connect socket io in dart. I use socket_io_client: ^2.0.0-beta.4-nullsafety.0 for connection and use this code to connect:
Socket socket = io(
'$server_address',
OptionBuilder()
.setTransports(['websocket'])
.disableAutoConnect()
.setExtraHeaders({'authorization': "$token"})
.build());
socket.connect();
And it connects successfully. But, my headers (authorization) are not sent to the server. I also check my request and response with inspect of google chrome to make sure:
So, How can I send the headers with socket io?
I think my answer is a bit late but it could help someone else. Anyway, I was facing the same issue and I found that socket_io_client in Flutter don't allow add extraHeader when you execute your app in the web (extraHeaders work fine in other platforms like Android or Windows), I think it is cause the securities restrictions of JavaScript when it's execute in a browser.
The solution that I found was use .setAuth({'authorization': "$token"})
instead of .setExtraHeaders({'authorization': "$token"})
. Your code should be like this:
final socket = io.io( url.toString(),
OptionBuilder()
.setTransports(['websocket'])
.disableAutoConnect()
.setAuth({'authorization': "$token" })
.build()
);
socket.connect();
In the server side, you can get your token using this: (This example is in NodeJS).
export const socketOnConnection = async ( socket : Socket, io : SocketServer ) => {
const token = socket.handshake.auth[ 'authorization' ] ;
// ... rest of your code here
}
I hope it be helpfull.
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