我们需要更多信息,例如:
- 你使用像 Angular 这样的 js 框架吗?
- 您是否使用 Bower 之类的工具来管理依赖关系?
- 您的 Sails 服务器是如何配置的?
最重要的是,我可以向您展示我如何配置 Sails 后端:
in my .sailsrc
我的钩子配置如下
"hooks": {
"csrf": false,
"grunt": false,
"i18n": false,
"pubsub": false,
"session": false,
"sockets": true,
"views": false}
然后在我的UserController.js
我有一个简单的方法可以启用套接字通信
enableNtofications: function(req, res){
// checking if the request comes from
// a socket request
if(req.isSocket){
// getting the current logged user
var user = req.user;
// subuscribing the client to model changes
User.subscribe(req, [user.id]);
return res.ok();
} else {
return res.badRequest();
}
},
我的前端使用 Angular 和ngSails https://github.com/janpantel/angular-sails是 Angular 的“sails.io”包装器的模块
在我的“UserService.js”中我可以做类似的事情
// waiting for notifications on User
$sails.on('user', function(event) {
if (event) {
// manage the message here...
}
});
然后调用服务器方法以启用套接字
// calling the service
return $sails.post('/user/enableNtofications').then(
// ok
function() {},
// ko
function(data) {
console.log("enable notifications KO");
console.log(data.error);
});
(您还需要注入 '$sails' 模块并正确配置它......)
希望这可以帮助你