【问题标题】:Node.js WebSockets - send data to server with BasicAuthNode.js WebSockets - 使用 BasicAuth 向服务器发送数据
【发布时间】:2017-11-26 03:07:28
【问题描述】:

我正在使用 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"}));
}

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

【问题讨论】:

    标签: node.js express websocket basic-authentication


    【解决方案1】:

    我建议您使用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,使用它inside app.ws('/', function (ws, req) {});来检查这个用户是否被授权。这是基本身份验证doc。希望你能解决这个问题!

    【讨论】:

    • 我必须在服务器端使用 express-ws。如果我只将客户端用作 socket.IO,这会起作用吗?
    • 是的,它只适用于 Socket.IO。我将尝试使用 express-ws 提供一个示例。
    • 如何检查您的服务器是否允许连接到客户端?尝试在连接时从服务器发送一些示例消息。然后就可以在客户端用这个函数ws.onmessage()查看了
    • 我设法从 ws.onmessage 处理程序中的服务器获得响应。 ws.onopen 处理程序还设法在连接打开时打印一行。但是当我从客户端向服务器发送消息时,没有消息到达。
    • 服务器端的“onmessage”监听器是什么样的?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多