我有一个基本的前端(html、css、jquery),我想使用sails.io.js与API服务器(使用have开发,启用cors )进行通信。API运行在localhost:10000上,但它将在另一个域上运行,而不是webclient上的域。
直接从jquery中,我可以向这个API发出一些get请求,并得到预期的结果。
说到websocket,我有一些问题.在index.html中(只是为了测试),我放置了以下内容:
<script src="js/sails.io.js"></script>
<script type="text/javascript">
io.sails.url('http://localhost:10000');
io.socket.get('/data', function serverResponded (body, sailsResponseObject) {
// body === sailsResponseObject.body
console.log('Sails responded with: ', body);
console.log('with headers: ', sailsResponseObject.headers);
console.log('and with status code: ', sailsResponseObject.statusCode);
});
</script>但是Chrome的开发工具告诉我
ReferenceError: io is not defined 知道吗?
更新
我为index.html提供web服务器(python -m SimpleHTTPServer)
我使用bower安装了sails.io.js。
我试着让这个测试尽可能简单:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<script src="bower_components/sails.io.js/dist/sails.io.js"></script>
<script src="index.js"></script>
</body>
</html>index.js:
window.onload=function(){
io.sails.url = 'http://localhost:10000';
io.socket.get('http://localhost:10000/data', function (body, response) {
console.log('Sails responded with: ', body);
});
};我的sails (0.9.16) API只是在GET /data路由上返回一个json对象。
我在api中实现了一个虚拟__getcookie函数:
'get /__getcookie': function(req, res, next){
res.json({ok: 123});
}并在interpret.js中对第481行进行了注释(斯科特注释如下)。
我还使用以下方法修改config/socket.js:
authorization: false,=>现在可以从API的/data路由获得结果:)
但是..。对于每个请求,我都有以下错误:
error: Error: No valid session available from this socket.发布于 2014-06-26 21:24:23
首先,sails.io.js包含了socket.io.js的代码,因此不需要分别尝试和包含这些代码。您应该删除这一行:
<script src="bower_components/socket.io/lib/socket.js"></script>接下来,如果您只是从磁盘加载index.html (而不是从web服务器提供服务),则需要告诉socket客户端要连接到哪个URL:
io.sails.url = 'http://localhost:10000';在开始进行套接字调用之前,将其放置在任何位置;库非常聪明,可以等到其连接后才进行调用。因此,总的来说:
window.onload=function(){
io.sails.url = 'http://localhost:10000';
io.socket.get('http://localhost:10000/data', function (body, sailsResponseObject) {
console.log('Sails responded with: ', body);
console.log('with headers: ', sailsResponseObject.headers);
console.log('and with status code: ', sailsResponseObject.statusCode);
});
};应该行得通。通过查找“成功连接的io.socket”,您应该能够在控制台中看到该套接字是否已连接。消息。
发布于 2014-06-26 03:15:40
https://stackoverflow.com/questions/24418179
复制相似问题