JSON.parse(e.data)-websocket的onmessage-ReferenceError:未定义e /未定义的'data'/ WebSocket已处于CLOSING或CLOSED状态

时间:2020-02-15 10:38:32

标签: javascript json websocket

websocket / JSON新手在这里。我从函数事件接收数据时遇到问题。有人可以帮我吗?

看起来消息已正确发送到服务器(使用sendMessage()函数时,message_cart值正确),但是在接收数据时发出了消息。

我的控制台:

websocket.min.js:35未捕获的TypeError:无法读取以下内容的属性“ data” 未定义 在receiveMessage(websocket.min.js:35)

从购物车到服务器的消息:10 //数字正确

websocket.min.js:83 WebSocket已经处于CLOSING或CLOSED状态。

我的websocket.js:

document.addEventListener('DOMContentLoaded', function(){
  'use strict';

  var ws_protocol = 'ws://';
  if (window.location.protocol == "https:")
    ws_protocol = 'wss://';
  var ws_url = ws_protocol + window.location.host + '/ws/auctions/' + qs;
  var webSocket = new WebSocket(ws_url);

  var amountbutton = document.getElementsByClassName('amountButton');
  var message_cart;

  webSocket.onopen = sendMessage();
  webSocket.onmessage = receiveMessage();

  function receiveMessage(e) {
    var msgData = JSON.parse(e.data);
    if ('auction_data' in msgData) {
        console.log("here we are, 'auction_data' in msgData");
    } else if ('cart_data' in msgData) {
        console.log("here we are, 'cart_data' in msgData");
    }
  };

  function sendMessage() {

    for(let i = 0; i < amountbutton.length; i++) {

      amountbutton[i].onclick = (e) => {
        if(!amountbutton[i].nextElementSibling) {
          message_cart = amountbutton[i].previousElementSibling.value;
          message_cart++;
        } else {
          message_cart = amountbutton[i].nextElementSibling.value;
          message_cart--;
        }
        console.log("message from cart to server: " + message_cart);
        webSocket.send(message_cart);
      }
    }
  }

  webSocket.onclose = function(e) {
    console.error('Websocket closed.');
  };

}, false);

1 个答案:

答案 0 :(得分:0)

为了使Web套接字调用onopenonmessage回调,您必须将它们分配给监听器,作为一个函数,而不是这些函数正在返回。因此,解决方案是仅分配这些功能而不调用它们,就像这样:

  webSocket.onopen = sendMessage; // <- no curly braces in there
  webSocket.onmessage = receiveMessage; // <- no curly braces in there

希望它会有所帮助:)