gpt4 book ai didi

javascript - 使用基本访问身份验证的 Web 套接字连接

转载 作者:搜寻专家 更新时间:2023-11-01 00:28:43 24 4
gpt4 key购买 nike

我正在尝试与需要基本访问身份验证的 Web 套接字建立连接(客户端)。从文档中我知道我应该使用 base64 加密的用户名和密码。它是 node.js 应用程序,所以我决定使用 npm 包 SockJS-client。这似乎是一个很好的解决方案,因为:

Under the hood SockJS tries to use native WebSockets first. If that fails it can use a variety of browser-specific transport protocols and presents them through WebSocket-like abstractions.

但我不知道如何使用基本访问身份验证建立连接。我试过 here 的解决方案, 但这个

var ws = new WebSocket("ws://username:password@example.com/service");

不起作用,我收到如下错误:

SyntaxError: The URL's scheme must be either 'http:' or 'https:'. 'ws:' is not allowed.

当我尝试使用 http/https 时,我得到了:

Error: InvalidStateError: The connection has not been established yet

当我想打电话的时候

sock.send('test');

像下面这样的另一个解决方案是不可能实现的,因为我无法访问 Web Socket 的服务器端。

var ws = new WebSocket("ws://example.com/service?key1=value1&key2=value2");

我不知道如何正确地与 Web Socket 建立经过身份验证的连接,如果您知道任何解决方案,请告诉我。

最佳答案

解决方案非常简单,但我认为值得将它放在这里供下一代使用。

最后我用ws实现了,你可以找here .首先,我添加了带有字段 Authorization 的 header ,其中包含编码的 token 。另一件事是将标志 perMessageDeflate 设置为 false

The client will only use the extension if it is supported and enabled on the server.

这就是代码的样子,对我来说工作得很好:

const WebSocket = require('ws');

const webSocket = new WebSocket(url, {
perMessageDeflate: false,
headers: {
Authorization: `Basic ${encodedToken}`,
},
});

webSocket.on('open', function open() {
console.log('Connection has been established.');
});

我希望它能为您节省很多时间。 👌🏻

关于javascript - 使用基本访问身份验证的 Web 套接字连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46998781/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com