Node.js WebSockets - 使用BasicAuth将数据发送到服务器

时间:2017-11-25 10:43:45

标签: node.js express websocket basic-authentication

我使用Node.js WebSockets(require(“ws”))来创建客户端和服务器。我还有正在运行服务器并使用基本身份验证的快速应用程序:

let app = express();
let bodyParser = require("body-parser");
let expressWs = require('express-ws');
expressWs(app);    
let auth = require('basic-auth');

let server = app.listen(8080);
app.use(auth);

现在我正在创建一个客户端websocket,我正在尝试连接到服务器websocket:

let WebSocket = require('ws');
let ws = new WebSocket("ws://user:pass@127.0.0.1:8080/");

使用前缀user:pass我设法与服务器建立连接。但现在我无法发送消息......

ws.onopen = function () {
    ws.send(JSON.stringify({type: "available", user: "user"}));
}

从我读到的所有内容中我认为我必须发送一些带有消息的标题,但我不知道如何。我将不胜感激任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

我建议您使用Socket.IO,因为它简化了WS的使用。这是使用Socket.IO完成基本身份验证的方式:

客户端

    <script src="/js/socket.io.js"></script>
    <script>
      var socket = io('127.0.0.1:8080', function() {
         transports: ['websocket']
         query: 'username=' + encodeURIComponent(username) + '&password=' + encodeURIComponent(password)
      });
      socket.on('connect', function() {
         // You will get here only if next() is passed with an empty body
         socket.emit('msg', { type: "available", user: "user" });
      });
    </script>

服务器端

this.io = require('socket.io').listen('8080');
this.io.use(function(socket, next) {
   // Getting auth data
   // 'request' contains the 'username' and 'password' variables you passed
   // from the client side
   var authData = socket.handshake.query
   //  Use authData to check if access granted for this user
   var accessGranted = this.checkAccess(authData);
   if (accessGranted) {
     // next() call will grant the connection between server and client
     next();
  }
});

有关详情,请参阅我上面提供的链接。

修改

我终于设法找到了这个。这一行app.use(auth);导致了这个问题。删除它,你会没事的。

如果您想使用basic-auth,请使用 app.ws('/', function (ws, req) {});内检查此用户是否已获得授权。这是基本身份验证doc。希望你能解决这个问题!

相关问题