0

I'm triying to develop a simple Hello World Websocket using Sails framework V0.12. I need to connect an external Basic Front-End (HTML,CSS,JS) to that Sails WebSocket server. Send a simple event and retrieving 'Hello World!!' I'm using Sails API sails.io.js.

I have tried this in Front-End

<!doctype html>
<html>

<head>
    <script type="text/javascript" src="js/dependencies/sails.io.js"></script>
    <script type="text/javascript">
    window.onload = function() {
        io.sails.url = 'http://localhost:1337';

        io.socket.get('http://localhost:1337/helloworld', function(body, sailsResponseObject) {
            console.log('Sails responded with: ', body);
            console.log('with headers: ', sailsResponseObject.headers);
            console.log('and with status code: ', sailsResponseObject.statusCode);
        });


    };
    </script>
</head>

<body>
    <ul id='messages'></ul>
    <button onclick="pagar()">Click me</button>
</body>

</html>

I know that is connecting to Sails, but I I'm not able to get WebSocket response. Sails response is 404 (Not found). How can i create that WebSocket Using Sails Socket. Thanks a lot!

Sergio David Romero
  • 236
  • 2
  • 6
  • 16
  • Try removing http://localhost:1337 from io.socket.get... I think sails socket client appends first parameter to io.sails.url. – hlozancic Feb 06 '17 at 09:47
  • I hope [this](http://stackoverflow.com/questions/40021125/sails-io-js-io-socket-get-user-not-implemented-in-core-yet/40027253#40027253) can help you – Andrea Rega Feb 09 '17 at 11:28
  • make sure in sails that config/routes.js contain a route to helloworld OR in config/blueprints.js has rest enabled – Tarek Feb 15 '17 at 20:20
  • for future reference, keep the url as http://[your_ip]:1337 so that you can share the front-end among multiple devices on the network – Paulo Jul 07 '17 at 04:41

1 Answers1

0

you can try this, working on sails 0.12

views/user/*.ejs

<div id='messages'></div>
<button id="pagar">Click me</button>
<script>
$('#pagar').click(function(){     
io.socket.post('/user/message', {message: 'hi world'});

});

</script>

api/controllers/UserController.js

  module.exports = {
      message: function(req, res) { 

            var io = sails.io;
            // emit to all sockets            
            io.sockets.emit('code', {message: req.param('message')});

        }
    }

//Front-End js assets/js/app.js

 io.socket.on('connect', function() {


    io.socket.on('code', function (data) {

         $("#messages").text(data.message);
        console.log('Sails responded: ', data.message);
    }
David Zambrano
  • 650
  • 7
  • 13