未捕获的 DOMException:在访问可用变量时尝试使用不可用或不再可用的对象
我正在编写一个与 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您在连接完全连接到服务器之前尝试通过 Websocket 连接发送某些内容时,通常会发生这种情况。因此,您应该做的是当服务器发送连接信号时运行代码,您可以使用事件侦听器“open”。在你的情况下,这将是:
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:
为了任何新访问者的缘故,这是我作为一个更实际的示例所做的(因为在
open
事件内发送消息并不总是这种情况):然后,按如下方式使用它(或者也许,使用
.then()
):注意:
我在
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):And then, use it as follow (or perhaps, using
.then()
):Note:
The reason why I'm adding
eventHandlers
insideconnect_ws()
function is, sincews
is a global var, addingeventHandlers
to it in global scope (outside the function) will run beforews
being initialized!p.s.: I'm not a pro at Node.js, feel free to correct me.