Reputation: 567
I am following the official Sails docs. Would like to implement the most basic socket functionality, i.e. client connects to a socket and when server notifies it about a response, executes a script.
The problem is that the socket requests are http and I am getting badRequest.
What's the right way to register a socket route in Sails?
My client code:
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);
});
The controller:
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'
});
}
}
The route:
'GET /sayhello': { action: 'project/api/app-socket' },
Upvotes: 1
Views: 203
Reputation: 37238
In your routes.js file you have:
'GET /sayhello': { action: 'project/api/app-socket' },
Add to this isSocket: true
. So make it:
'GET /sayhello': { action: 'project/api/app-socket', isSocket: true },
How I learned this?
The convention for subscribe endpoints is to use an action prefixed with "subscribe", so when I generated an action with this command and this prefix:
sails generate action task/subscribe-to-task
Then it gave me this hint in the terminal output:
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 },
That's how I learned that we needed to add isSocket: true
.
Upvotes: 1