未捕获的 DOMException:在访问可用变量时尝试使用不可用或不再可用的对象

发布于 2025-01-10 00:13:28 字数 548 浏览 0 评论 0原文

我正在编写一个与 websocket 服务器通信的客户端。目前,套接字服务器向客户端发送生成的“令牌”,然后客户端将其设置为存储:

      localStorage.setItem('token', json.token);

并重定向到下一页,该页面在加载时运行此代码:

token = localStorage.getItem('token')


console.log(token)



socket.send(JSON.stringify({"type": "getplayerinfo", "token": token}));

当执行 console.log(token) 时,我得到令牌。然而,当通过套接字发送令牌时,我得到:

Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable

我已经调试了三天并且伤透了我的大脑。有什么建议吗?

I'm writing a client that communicates with a websocket server. Currently, the socket server sends a generated "token" to the client, which then sets it in storage with:

      localStorage.setItem('token', json.token);

And redirects to the next page, which on load, runs this code:

token = localStorage.getItem('token')


console.log(token)



socket.send(JSON.stringify({"type": "getplayerinfo", "token": token}));

When doing console.log(token), I get the token. However, when sending the token through the socket, I get:

Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable

I've been debugging this for 3 days and have wracked my brain. Any tips?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

伴我老 2025-01-17 00:13:28

当您在连接完全连接到服务器之前尝试通过 Websocket 连接发送某些内容时,通常会发生这种情况。因此,您应该做的是当服务器发送连接信号时运行代码,您可以使用事件侦听器“open”。在你的情况下,这将是:

const socket = new Websocket(url);
socket.addEventListener("open", (ev) => {
  socket.send(JSON.stringify({"type": "getplayerinfo", "token": token}));
  });

This normally happens when you try to send something through a websocket connection before the connection has fully connected to the server. So what you should do is run the code when the server sends a connected signal which you can using the event listener "open". In your case this would be:

const socket = new Websocket(url);
socket.addEventListener("open", (ev) => {
  socket.send(JSON.stringify({"type": "getplayerinfo", "token": token}));
  });

℉絮湮 2025-01-17 00:13:28

为了任何新访问者的缘故,这是我作为一个更实际的示例所做的(因为在 open 事件内发送消息并不总是这种情况):

let ws;    //Global var

async function connect_ws()
{
    return new Promise( resolve =>
    {
        ws = new WebSocket("ws://localhost:12345");

        ws.addEventListener("open", event => {
            console.log("Connected to WS server!");
            resolve();
        });

        ws.addEventListener("message", ( {data} ) => {
            console.log("WS server says: ", JSON.parse(data) );
        });
    });
}

function send_ws(msg)
{
    console.log("Sending message:", msg);
    ws.send(msg);
}

然后,按如下方式使用它(或者也许,使用 .then()):

await connect_ws();
send_ws( JSON.stringify(obj) );

注意:

我在 connect_ws() 函数中添加 eventHandlers 的原因是,因为 ws 是一个全局变量,添加全局范围内(函数外部)的 eventHandlers 将在 ws 初始化之前运行!

ps:我不是 Node.js 的专业人士,请随时纠正我。

For the sake of any new visitors, here's what I do as for a more practical example (since sending message right inside open event is not always the case):

let ws;    //Global var

async function connect_ws()
{
    return new Promise( resolve =>
    {
        ws = new WebSocket("ws://localhost:12345");

        ws.addEventListener("open", event => {
            console.log("Connected to WS server!");
            resolve();
        });

        ws.addEventListener("message", ( {data} ) => {
            console.log("WS server says: ", JSON.parse(data) );
        });
    });
}

function send_ws(msg)
{
    console.log("Sending message:", msg);
    ws.send(msg);
}

And then, use it as follow (or perhaps, using .then()):

await connect_ws();
send_ws( JSON.stringify(obj) );

Note:

The reason why I'm adding eventHandlers inside connect_ws() function is, since ws is a global var, adding eventHandlers to it in global scope (outside the function) will run before ws being initialized!

p.s.: I'm not a pro at Node.js, feel free to correct me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文