WebSocket JS 的自定义标头 [英] Custom headers for WebSocket JS

查看:133
本文介绍了WebSocket JS 的自定义标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一个简单的解决方案,将 WebSocket 与自定义标头结合使用,用于基于 PHP 作为后端和 js+vuejs 作为前端的 Web 应用程序.

I finding a simple solution to use WebSocket with custom headers for web app based on PHP as backend and js+vuejs as frontend.

我的应用程序应该连接到基于 Java 的 WebSocket 服务器以获取实时统计信息.受 Oauth2 保护的 WebSocket 服务器.所以我的应用程序应该添加像

My app should connect to WebSocket server based on Java to get live stat. WebSocket server protected by Oauth2. So my app should add header like

授权:承载 647d14-b132-41b9-aa4c-9eafad5d9630"

"Authorization: bearer 647d14-b132-41b9-aa4c-9eafad5d9630 "

当连接到 WS 服务器时.但我无法添加此标题,因为浏览器不支持自定义标题.回答有关自定义标头的问题 Websockets 客户端 API 中的 HTTP 标头

when connect to WS server. But i can't add this header because browser doesn't support custom headers. Answer on question about custom headers HTTP headers in Websockets client API

我需要类似下面的代码

var serverWs = "ws://servername/stat"; var opts = { reconnection: false, transports: ['websocket'], extraHeaders: { 'Authorization': 'Bearer xxxx' } } var ws = new WebSocket(serverWs, opts);

有什么解决方案?

推荐答案

Websocket 客户端 API 不允许发送自定义标头,它们允许您只设置一个标头,即 Sec-WebSocket-Protocol,即应用程序特定的子协议.您可以使用此标头传递不记名令牌.

Websocket client API doesn't allow to send custom header, they allow you to set exactly one header, namely Sec-WebSocket-Protocol, i.e. the application specific subprotocol. You could use this header for passing the bearer token.

其他选项是在查询字符串中使用令牌.

Other option is to use token in query string.

或者您可以在客户端或服务器上使用一些支持自定义标头实现的库,例如.https://github.com/crossbario/autobahn-python/tree/master/examples/twisted/websocket/echo_httpheaders

Or you can use some library on client or server which support custom headers implementation eg. https://github.com/crossbario/autobahn-python/tree/master/examples/twisted/websocket/echo_httpheaders

这篇关于WebSocket JS 的自定义标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆