我正在尝试使用Sails框架V0.12开发一个简单的Hello World Websocket。我需要将外部基本前端(HTML,CSS,JS)连接到该Sails WebSocket服务器。发送一个简单的事件并检索“Hello World !!'我正在使用Sails API sails.io.js。
我在前端尝试了这个
<!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>
我知道这是连接到Sails,但我无法获得WebSocket响应。 Sails响应为404(未找到)。如何使用Sails Socket创建WebSocket。非常感谢!
答案 0 :(得分:0)
视图/用户/ *。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 /控制器/ UserController.js
module.exports = {
message: function(req, res) {
var io = sails.io;
// emit to all sockets
io.sockets.emit('code', {message: req.param('message')});
}
}
//前端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);
}