【问题标题】:SailsJs websocket with a custom route instead of blueprint?SailsJs websocket 使用自定义路由而不是蓝图?
【发布时间】:2019-03-25 17:42:38
【问题描述】:

我正在关注官方 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】:

    在你的 routes.js 文件中你有:

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

    添加到此isSocket: true。就这样吧:

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

    我是怎么学会的?

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

    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

    【讨论】:

      猜你喜欢
      • 2014-09-16
      • 1970-01-01
      • 2015-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多