【问题标题】:JSON.parse(e.data) - websocket's onmessage - ReferenceError: e is not defined / 'data' of undefined / WebSocket is already in CLOSING or CLOSED stateJSON.parse(e.data) - websocket 的 onmessage - ReferenceError: e is not defined / 'data' of undefined / WebSocket 已经处于 CLOSING 或 CLOSED 状态
【发布时间】:2020-05-30 22:30:41
【问题描述】:

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

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

我的控制台:

websocket.min.js:35 Uncaught TypeError: Cannot read property 'data' of 不明确的 在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);

【问题讨论】:

    标签: javascript json websocket


    【解决方案1】:

    为了让网络套接字调用您的 onopenonmessage 回调,您必须将它们作为函数分配给侦听器,而不是作为 这些函数正在返回。所以解决方案是只分配这些函数而不调用它们,就像这样:

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

    希望对你有帮助:)

    【讨论】:

      猜你喜欢
      • 2016-09-09
      • 2014-09-10
      • 2019-04-13
      • 1970-01-01
      • 2018-07-06
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 2019-01-03
      相关资源
      最近更新 更多