API request from frontend using sails.io.js

I have a basic interface (html, css, jquery), and I would like to use sails.io.js to communicate with the API server (designed using sails with cors enabled). The API runs on localhost: 10000, but later it will be in a different domain than the one that is part of the web client.

Directly from jquery, I can request some request to get this API and get the expected results.

When it comes to websocket, I have some problems ... In index.html (just for verification), I put the following:

<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>

But Chrome developer tools tell me

ReferenceError: io is not defined 

Any idea?

UPDATE

I am serving index.html with a web server (python -m SimpleHTTPServer)
I installed sails.io.js using the gazebo.

:

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 json GET/data.

api __getcookie:

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

481 interp.js( ).

config/socket.js :

 authorization: false,

= > /data API:)

... :

error: Error: No valid session available from this socket.
+4
2

, sails.io.js socket.io.js, . :

<script src="bower_components/socket.io/lib/socket.js"></script>

, index.html ( -), 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, ." .

+3
  • / src, :

    < script src= "js/sails.io.js" >

  • sails.io.js /assets/js/( 0.10) /assets/linker/js ( 0.9 ).

  • js .tmp/public/js?

  • index.html?

0

Source: https://habr.com/ru/post/1546050/


All Articles