首页 > 解决方案 > 使用事件的feathersjs套接字

问题描述

在feathersjs 文档中,例如here,推荐的调用服务器的方法是发出一个事件。为什么不直接调用应用程序呢?那么为什么要使用:

socket.emit('find', 'messages', { status: 'read', user: 10 }, (error, data) => {
  console.log('Found all messages', data);
});

当您可以简单地执行以下操作时:

app.service('messages').find({ query: { status: 'read', user: 10 } }) 

这只是人们更喜欢事件符号还是有其他论据需要考虑?

标签: javascriptsocketsdom-eventsfeathersjs

解决方案


您链接的文档页面解释了如何直接使用 websocket - 例如,如果您连接 Android 应用程序或不想/不能在客户端上使用 Feathers。

建议尽可能在客户端上使用 Feathers,它会在后台自动为您做完全相同的事情。像这样的客户端代码:

const io = require('socket.io-client');
const feathers = require('@feathersjs/feathers');
const socketio = require('@feathersjs/socketio-client');

const socket = io('http://api.my-feathers-server.com');
const app = feathers().configure(socketio(socket));

app.service('messages').find({ query: { status: 'read', user: 10 } })
  .then(data => console.log('Found all messages', data));

做同样的事情

const io = require('socket.io-client');
const socket = io('http://api.my-feathers-server.com');

socket.emit('find', 'messages', { status: 'read', user: 10 }, (error, data) => {
  console.log('Found all messages', data);
});

但首先你会获得 Feathers 应用程序的优点(钩子、事件、承诺、身份验证)和熟悉度。


推荐阅读