如何在flutter中向socketIO添加标头
我尝试在 dart 中连接套接字 io。我使用 socket_io_client: ^2.0.0-beta.4 -nullsafety.0 用于连接并使用此代码进行连接:
Socket socket = io(
'$server_address',
OptionBuilder()
.setTransports(['websocket'])
.disableAutoConnect()
.setExtraHeaders({'authorization': "$token"})
.build());
socket.connect();
并且连接成功。但是,我的标头(授权)没有发送到服务器。我还使用 google chrome inspect 检查我的请求和响应,以确保:
< img src="https://i.sstatic.net/9NYeu.png" alt="Screenshot">
那么,如何使用套接字 io 发送标头?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为我的回答有点晚了,但它可以帮助其他人。无论如何,我面临着同样的问题,我发现 Flutter 中的 socket_io_client 不允许在网络中执行应用程序时添加 extraHeader(extraHeaders 在 Android 或 Windows 等其他平台上工作正常),我认为这是导致安全限制的原因JavaScript 在浏览器中执行时的情况。
我找到的解决方案是使用
.setAuth({'authorization': "$token"})
而不是.setExtraHeaders({'authorization': "$token"})
。你的代码应该是这样的:在服务器端,你可以使用这个来获取你的令牌:(这个例子是在 NodeJS 中)。
我希望它有帮助。
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:In the server side, you can get your token using this: (This example is in NodeJS).
I hope it be helpfull.