SailsJs websocket与自定义路线而不是蓝图?

问题描述 投票:1回答:1

我正在关注官方Sails docs。想要实现最基本的套接字功能,即客户端连接到套接字,当服务器通知它有关响应时,执行脚本。

问题是套接字请求是http,我得到badRequest。

在Sails中注册套接字路由的正确方法是什么?

我的客户代码:

io.socket.on('hello', function (data) {
    console.log('Socket `' + data.id + '` joined the party!')
  })
io.socket.get('/sayhello', function gotResponse(data, jwRes) {
    console.log('Server responded with status code ' + jwRes.statusCode + ' and data: ', data);
  });

控制器:

module.exports = {
exits: {
    badRequest: {
      responseType: 'badRequest',
      description: 'The provided data is invalid.',
    },
},
fn: async function (req, res) {
  if (!req.isSocket) {
    return res.badRequest();
  }
  sails.sockets.join(req, 'funSockets');
  sails.sockets.broadcast('funSockets', 'hello', {howdy: 'hi there!'}, req);
  return res.json({
    anyData: 'we want to send back'
  });
}

}

路线:

'GET /sayhello':   { action: 'project/api/app-socket' },
javascript sockets sails.js
1个回答
1
投票

在routes.js文件中,您有:

'GET /sayhello':   { action: 'project/api/app-socket' },

添加到此isSocket: true。所以做到:

'GET /sayhello':   { action: 'project/api/app-socket', isSocket: true },

我是怎么学到这个的?

订阅端点的约定是使用前缀为“subscribe”的操作,因此当我使用此命令和此前缀生成操作时:

sails generate action task/subscribe-to-task

然后它在终端输出中给了我这个提示:

Successfully generated:
 •- api/controllers/task/subscribe-to-task.js

A few reminders:
 (1)  For most projects, you'll need to manually configure an explicit route
      in your `config/routes.js` file; e.g.
          'GET /api/v1/task/subscribe-to-task': { action: 'task/subscribe-to-task', isSocket: true },

这就是我了解到我们需要添加isSocket: true的方法。

© www.soinside.com 2019 - 2024. All rights reserved.