带有 vue-socket-io 的 VueJS 不显示任何内容 [英] VueJS with vue-socket-io not displaying anything
问题描述
尝试了几天但没有任何运气.我安装了 https://www.npmjs.com/package/vue-socket.io.
Trying for days but without any luck. I installed https://www.npmjs.com/package/vue-socket.io.
然后我将此代码添加到我的 main.js vue 文件中:
I then added this code to my main.js vue file:
import VueSocketio from 'vue-socket-io';
Vue.use(VueSocketio, 'http://localhost:3001/');
我的节点服务器在端口 3001 上运行,当我刷新页面时,我确实看到发生了一些事情,即命令提示符显示一个随机字符串,即PLlVSTMrfO2BzCJAAAZ".这是我的连接,所以这部分工作正常!
My node server is running on port 3001, and when I refresh my page I do see something happen i.e. the command prompt shows a random string i.e. "PLlVISTMrfO2BzCJAAAZ". This is my connection, so that part is working!
当我想从我的服务器接收消息时,我使用了以下代码:
When I want to receive a message from my server I used this code:
io.on('connection', function(socket) {
console.log('connected with id: ' + socket.id)
socket.on('SEND_MESSAGE', function(data) {
io.emit('hello_world', 'Get you right back...')
console.log(data);
});
});
当我从 Vue 发送消息时,它被服务器接收,但是当我尝试从服务器向 Vue 发送消息时,它从未收到.
When I send a message from Vue, it is received by the server, but when I try to send a message from the server to Vue it is never received.
我的 Vue 代码:
created() {
// Send a message to the server
this.$socket.emit('SEND_MESSAGE', 'Hello Node!')
// Listen
this.$options.sockets.hello_world = (data) => {
console.log(data);
console.log('something came...');
}
}
有人知道如何解决这个问题吗?我也试过这个,但这也行不通:
Does anyone have any idea how to fix this? I also tried this but this aint working either:
sockets: {
connect() {
// Fired when the socket connects.
console.log("server connected");
},
disconnect() {
console.log("server disconnected");
},
hello_vue: function (data) {
console.log('this method was fired by the socket server. eg: io.emit("customEmit", data)')
}
}
推荐答案
您链接的 npm 来源说您必须订阅事件才能在期间动态接收它们运行时.
The npm source you linked says that you have to subscribe to events to receive them dynamically, during runtime.
this.sockets.subscribe('EVENT_NAME', (data) => {
this.msg = data.message;
});
this.sockets.unsubscribe('EVENT_NAME');
您可以在此处找到它.
您的代码是根据 旧文档(我猜它已被弃用,不再有效).
Your code is written according to the old documentation (I guess that's deprecated, no longer working).
我建议您使用订阅方法尝试一下.
I suggest you try it with the subscribe method.
编辑
解决方案是将使用过的socket包更新为更好的,并处理节点服务器中的CORS错误.
The solution was to update the used socket package to a better one, and handle the CORS errors in the node server.
新的、更好的包:npmjs.com/package/vue-socket.io-扩展
CORS 错误处理:https://enable-cors.org/server_expressjs.html
重要修改
GitHub 通知我,它在本示例中使用的一个依赖项中发现了高严重性漏洞.
GitHub informed me, that it found a HIGH SEVERITY VULNERABILITY in one of the dependencies used in this example.
CVE-2018-20834
更多信息
高严重性
易受攻击的版本:<4.4.2
补丁版本:4.4.2
在 4.4.2 版本之前的 node-tar 中发现了一个漏洞.将包含硬链接的 tarball 与系统上已存在的文件结合使用与硬链接同名的后续纯文件时,存在任意文件覆盖问题.此纯文件内容替换现有文件内容.
请小心!
这篇关于带有 vue-socket-io 的 VueJS 不显示任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!