使用sails.io.js从前端请求API



我有一个基本的前端(html, css, jquery),我想使用sails.io.js与API服务器通信(与sails开发,启用cors)。该API在localhost:10000上运行,但它将在另一个域中运行,而不是web客户端。

直接从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);
    });
};

My sails (0.9.16) API只在GET/data路由上返回json对象。

我在api中实现了一个虚拟__getcookie函数:

'get /__getcookie': function(req, res, next){
    res.json({ok: 123});
}

并注释了interpreter .js中的第481行(Scott在下面注释)。

我还修改了config/socket.js:

 authorization: false,

=>我现在可以从我的API的/data路由获得结果:)

但是…对于每个请求,我都有以下错误:

error: Error: No valid session available from this socket.

首先,sails.io.js包含了socket.io.js的代码,所以没有必要尝试单独包含它。你应该删除这一行:

<script src="bower_components/socket.io/lib/socket.js"></script>
接下来,如果你只是从磁盘加载index.html(而不是从web服务器提供),你需要告诉Sails套接字客户端要连接到哪个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 connected successfully."消息,您应该能够在控制台中看到套接字是否已连接。

  1. 你有没有试过在src前面加一个/,比如:

    & lt;js/sails.io.js script src = " ">

  2. sails.io.js在/assets/js/文件夹(sails0.10)还是在/assets/linker/js文件夹(sails0.9及以下)

  3. 船帆升降机复制的js文件到。tmp/public/js文件夹?

  4. 你的index.html文件在哪里?

最新更新