首页 > 解决方案 > 自定义事件不会从 feathersjs 发送到 feathers-vuex

问题描述

嗨,我正在开发一个 feathersjs 后端(TS)。我希望能够将自定义事件(扫描的条形码)发送到我的 feathers-vuex 前端。

我在后端使用羽毛 cli 生成了一个自定义服务。我在服务中注册了我的自定义事件,如下所示:

export default function (app: Application): void {
  const options = {
    paginate: app.get('paginate'),
    events: ['barcode_scanned'] <--- my custom event 
  };

  // Initialize our service with any options it requires
  app.use('/scans', new Scans(options, app));

  // Get our initialized service so that we can register hooks
  const service = app.service('scans');

  service.hooks(hooks);
}

在我的中间件文件夹中,我使用以下代码发送事件:

export default function (app: Application): void {
  app.post('/scan', async (req, res) => {
    const code = req.body.code;
    if (code) {
      Logger.info(`Scanned product with barcode '${code}'`);
      app.service('scans').emit('barcode_scanned', code); <--- code used to send
      res.sendStatus(200);
    } else {
      res.sendStatus(500);
    }
  });

在我的 feathers-vuex 前端中,我使用此代码来监听事件。

feathersClient.service('scans')
  .on('barcode_scanned', message => console.log('New message created', message));

但是没有消息通过。所以我检查了 chrome dev-tools 中的 Network 选项卡,但没有收到任何消息。

我还用wireshark检查了网络,当我触发我的事件时,发现WebSocket上没有流量。

当我调试我的羽毛应用程序时,我得到了这个输出(在触发器上)

express:router dispatching POST /scan +9s
  express:router query  : /scan +0ms
  express:router expressInit  : /scan +1ms
  express:router helmetMiddleware  : /scan +0ms
  express:router corsMiddleware  : /scan +0ms
  express:router compression  : /scan +0ms
  express:router jsonParser  : /scan +0ms
  body-parser:json content-type "application/json; charset=utf-8" +9s
  body-parser:json content-encoding "identity" +1ms
  body-parser:json read body +0ms
  body-parser:json parse body +0ms
  body-parser:json parse json +0ms
  express:router urlencodedParser  : /scan +1ms
  body-parser:urlencoded body already parsed +0ms
  express:router favicon  : /scan +1ms
  express:router serveStatic  : /scan +0ms
  express:router <anonymous>  : /scan +0ms
  express:router <anonymous>  : /scan +0ms
  @feathersjs/authentication/base Strategies parsing HTTP header for authentication information [ 'jwt', 'local' ] +9s
[info] - [alh] : Aug-10-2021 11:42:10 : Scanned product with barcode 'J-12829'
  compression no compression: size below threshold +9s
  engine:ws received "2" +26s
  engine:socket packet +26s
  engine:socket got ping +3ms
  engine:socket sending packet "pong" (undefined) +1ms
  engine:socket flushing buffer to transport +0ms
  engine:ws writing "3" +5ms

所以我必须对我的服务器代码做错事(我认为),但不知道该怎么做。

标签: websocketsocket.iofeathersjsfeathers-vuex

解决方案


推荐阅读