我必须在我的angular 2项目中使用Websocket连接我在创建Websocket连接时遇到问题,出现错误'WebSocket连接到'ws://localhost:8081/…/…/..'失败:HTTP身份验证失败;没有可用的有效凭据'这是我的代码
var socket = new WebSocket('ws:localhost:8081/../../..');
我已经累了好几天了。请任何知道这件事的人帮助我。
致以最诚挚的问候
您可以从rxjs库中创建websocket包装器。
像这样导入:
import {webSocket, WebSocketSubject} from 'rxjs/webSocket';
然后创建这样一个:
private webSocket: WebSocketSubject = webSocket(environment.chatUrl);
然后你可以订阅它来获得入站消息:
this.subscription = this.webSocket.subscribe(
msg => {
// do something with the message
},
err => {
// handle the error
console.log('error!', err);
},
() => {
// handle getting disconnected
console.log('websocket closed');
}
);
并发送一条消息:
this.webSocket.next(message);
完成后不要忘记取消订阅网络套接字。
发生这种情况的原因如下您的http url和websocket url在身份验证时不匹配
你的http url是
http://localhost:port/something..
并且您的websocket url是var webs = new WebSocket("ws://192.168...:port/something..");
反之亦然
要解决此问题,请保持两个url相同的