我正在遵循官方的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' },
答案 0 :(得分: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
的方式。