javascript - 如何在javascript中创建websocket时发送自定义标头?
问题描述
所以我在 Python 上创建了一个 websocket 连接的以下代码:
channels_dict = {}
channels_dict['Authorization'] = 'true'
for channel in channels: #adds some extra headers with info
channels_dict["Channel" + str(channel)] = '1'
ws = websocket.WebSocketApp("ws://localhost:8888/ws",
on_message = on_message,
on_error = on_error,
on_close = on_close,
header = channels_dict)
而且我可以轻松添加额外的标头,以便稍后在连接时在服务器中访问。有没有办法我可以在 Javascript 中做同样的事情?我没有找到太多关于在 websocket 创建中设置自定义标头的信息。我在 JS 中有以下代码:
var webSocket;
function openWebsocket() {
webSocket = new WebSocket("ws://localhost:8888/ws")
}
我听说在 url 中添加查询参数,这是在 javascript 中向 websocket 连接添加额外标头/信息的唯一方法吗?
解决方案
尝试这个:
const webSocket = new WebSocket ("ws://localhost:8888/ws" + "?param1=" + param1); // here you can add other params
webSocket.on("open", function open(e) {
console.log("*** websocket opened");
});
推荐阅读
- scala - Spark作业长时间无结果运行
- triggers - 如何在收到欢迎电子邮件后的下周五开始 MailChimp 活动
- python - 如何编写正则表达式以使整个正则表达式成为包含两个可能组的集合?
- javascript - 如何在 Javascript 中的选择中创建多个选项
- php - mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'xpto'@'localhost' (使用密码: YES)
- python - 如何生成具有不同稀疏度的二进制模式?
- hadoop - 无法在 AWS EC2 实例上启动 HDP2.6.1 Sandbox 的大部分服务
- asp.net-core - 如何让单个控制器和操作处理 asp.net 核心中的所有路由?
- r - 尝试将数据插入空数据框时出错
- android - 回购中缺少示例?