使用自定义路由而不是蓝图的 SailsJs websocket?
SailsJs websocket with a custom route instead of blueprint?
我正在关注官方 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' },
在您的 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
。
我正在关注官方 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' },
在您的 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
。