Giter Club home page Giter Club logo

sails.io.js's Introduction

icon of a life preserver - the emblem of the sails client SDK Sails JavaScript Client SDK

NPM version    

JavaScript SDK for communicating w/ Sails via sockets from Node.js or the browser.

For Node.js

Why would I use this from a Node script?

Most commonly, this SDK is useful on the backend when writing tests. However, any time you'd want to use a WebSocket or Socket.io client from Node to talk to a Sails server, you can use this module to allow for the ordinary usage you're familiar with in the browser-- namely using the socket interpreter to simulate HTTP over WebSockets.

Installation

$ npm install socket.io-client --save
$ npm install sails.io.js --save

Basic Usage

var socketIOClient = require('socket.io-client');
var sailsIOClient = require('sails.io.js');

// Instantiate the socket client (`io`)
// (for now, you must explicitly pass in the socket.io client when using this library from Node.js)
var io = sailsIOClient(socketIOClient);

// Set some options:
// (you have to specify the host and port of the Sails backend when using this library from Node.js)
io.sails.url = 'http://localhost:1337';
// ...

// Send a GET request to `http://localhost:1337/hello`:
io.socket.get('/hello', function serverResponded (body, JWR) {
  // body === JWR.body
  console.log('Sails responded with: ', body);
  console.log('with headers: ', JWR.headers);
  console.log('and with status code: ', JWR.statusCode);

  // ...
  // more stuff
  // ...


  // When you are finished with `io.socket`, or any other sockets you connect manually,
  // you should make sure and disconnect them, e.g.:
  io.socket.disconnect();

  // (note that there is no callback argument to the `.disconnect` method)
});

See the tests in this repository for more examples.

========================================

For the browser

The sails.io.js client comes automatically installed in new Sails projects, but there is nothing app-specific about the client SDK. You can just as easily copy and paste it yourself, get it from Bower, or just link a script tag directly to a hosted CDN.

Always use the version of sails.io.js that is compatible with your version of Sails. The master branch of this repository includes the bleeding edge version of sails.io.js that is compatible with the master branch of Sails core and of sails-hook-sockets. If you have an older install, use the copy of sails.io.js that is included in the assets/ folder of your Sails app.

  </body>

  <!-- Import SDK (if using the linker, then this will be injected automatically) -->
  <script type="text/javascript" src="/dependencies/sails.io.js"></script>

  <!-- Example usage -->
  <script type="text/javascript">

    // `io` is available as a global.
    // `io.socket` will connect automatically, but at this point in the DOM, it is not ready yet
    // (think of $(document).ready() from jQuery)
    //
    // Fortunately, this library provides an abstraction to avoid this issue.
    // Requests you make before `io` is ready will be queued and replayed automatically when the socket connects.
    // To disable this behavior or configure other things, you can set properties on `io.sails`.
    // You have one cycle of the event loop to set `io.sails.autoConnect` to false before the auto-connection
    // behavior starts.

    io.socket.get('/hello', function serverResponded (body, JWR) {

      // JWR ==> "JSON WebSocket Response"
      console.log('Sails responded with: ', body);
      console.log('with headers: ', JWR.headers);
      console.log('and with status code: ', JWR.statusCode);

      // first argument `body` === `JWR.body`
      // (just for convenience, and to maintain familiar usage, a la `JQuery.get()`)
    });
  </script>
</html>

========================================

Advanced usage

The io.sails config functions as the default for all connected sockets, allowing you to change client behavior globally. It can be overridden on a socket-by-socket basis by passing in an object to io.sails.connect(opts)

Cross-domain

Connect to a server other than the one that served ths project (i.e. on a different domain/subdomain):

<script type="text/javascript" src="/dependencies/sails.io.js"></script>
<script type="text/javascript">
io.sails.url = 'https://api.mysite.com';
</script>

Note that in order for req.session on a cross-domain server to work, there is a bit of pregaming that sails.io.js does behind the scenes. This is because it relies on cookies, and browsers (thankfully) do not let us access cross-origin cookies. This JavaScript SDK circumvents that issue by (1) detecting a cross-origin scenario by examining window.location (if available) and comparing it with the connection base URL, then (2) sending a JSONP request to the cross-origin server in order to gain access to a cookie. In order for that to work, the cross-origin sails server must have CORS enabled for http://yourdomain.com so that 3rd-party cookies are granted with the JSONP request. Fortunately, Sails supports this behavior out of the box.

For example, imagine the sails.io.js client is being used on a webpage served from a Sails server (or any other kind of server, like nginx) at http://yourdomain.com, but you need to connect a WebSocket to a different Sails server at http://api.your-other-domain.com. First, sails.io.js will send a JSONP request to the configured "cookie route" (i.e. /__getcookie by default). That particular "cookie route" comes with CORS enabled out of the box, which means it will grant cookies to 3rd party domains. In your config/sockets.js file, you can restrict cross-domain cookie access to particular domains (i.e. http://yourdomain.com, in this example)

Disable autoConnect and/or connect sockets manually

Disable io.socket and its auto-connecting behavior and/or connect 1 or more sockets manually:

<script type="text/javascript" src="/dependencies/sails.io.js"></script>
<script type="text/javascript">
io.sails.autoConnect = false;

// e.g. at some point later, connect 3 sockets, using default settings
setTimeout(function (){

  // socket0 and socket1 will use default settings from `io.sails`
  var socket0 = io.sails.connect();
  var socket1 = io.sails.connect();

  // but socket2's `url` option will be overridden as specified:
  var socket2 = io.sails.connect('https://api.mysite.com');
}, 1000);
</script>
Send custom headers with socket handshake using initialConnectionHeaders

Disable session support for all connecting sockets

<script type="text/javascript" src="/dependencies/sails.io.js"></script>
<script type="text/javascript">
io.sails.initialConnectionHeaders = {nosession: true};
</script>

Disable session support on a per-socket basis

<script type="text/javascript" src="/dependencies/sails.io.js"></script>
<script type="text/javascript">
io.sails.autoConnect = false;
// socket 1 will have session disabled
var socket1 = io.sails.connect('http://localhost', {initialConnectionHeaders: {nosession: true}});
// socket 2 will have session enabled
var socket2 = io.sails.connect('http://localhost');
</script>
Set global headers to be used with each socket request

Set a x-csrf-token header to be sent with every request made using io.socket.* methods:

<script type="text/javascript" src="/dependencies/sails.io.js"></script>
<script type="text/javascript">
io.sails.headers = {
  "x-csrf-token": someToken,
};
// This POST request will now include the x-csrf-token header
io.socket.post("/foo", someData, someCallback);
</script>
Change the transports used to connect to the server

In some cases you may want to change the transorts that the socket client uses to connect to the server, and vice versa. For instance, some server environments--notably Heroku--do not support "sticky load balancing", causing the "polling" transport to fail. In these cases, you should first change the transports listed in the config/sockets.js file in your Sails app. Then change the transports in the client by setting io.sails.transports:

<script type="text/javascript" src="/dependencies/sails.io.js"></script>
<script type="text/javascript">
  io.sails.transports = ['websocket'];
</script>
Change the rejectUnauthorized setting used to connect to the server

As of socket.io-client version 1.4.6 and engine.io-client 1.6.9, if you are using SSL certificates to connect, rejectUnauthorized defaults to true if not explicitly set. To keep the old behavior (useful for development and testing/continuous integration environments), set it to false on the io.sails object:

<script type="text/javascript" src="/dependencies/sails.io.js"></script>
<script type="text/javascript">
  io.sails.rejectUnauthorized = false;
</script>

RequireJS/AMD Usage

To use this in an AMD environment, use the sails.io.js in the root of this repo, not in dist. The dist build bundles a version of the socket.io client which will cause errors when trying to load two anonymous AMD modules from the same file. The file in root is not bundled with socket.io

Usage with AMD will be very similar as node. Require in sails.io, socket.io, and instantiate the sails.io client:

define(['path/to/socketIOClient', 'path/to/sailsIOClient'], function(socketIOClient, sailsIOClient)  {
    var io = sailsIOClient(socketIOClient);
    io.sails.url = 'http:/example.com';

    io.socket.get('/example/path', { data: 'example' }, function(response) {
        console.log('got response', response)
    });
});
Muting console.log messages

Sails.io.js console.log messages are automatically muted in production environments. You can set the environment manually via io.sails.environment:

<script type="text/javascript" src="/dependencies/sails.io.js"></script>
<script type="text/javascript">
  io.sails.environment = 'production';
</script>

If not specified manually, sails.io.js will assume the development environment unless it is loaded from a URL that ends in *.min.js or #production, e.g. production.min.js or scripts.js#production.

========================================

Help

If you have further questions or are having trouble, click here.

Bugs   NPM version

To report a bug, click here.

Contributing   Build Status

Please observe the guidelines and conventions laid out in the Sails project contribution guide when opening issues or submitting pull requests.

NPM

NPM

This repository holds the socket client SDK for Sails versions 0.11.0 and up. If you're looking for the SDK for the v0.9.x releases of Sails, the source is located here. If you're looking for v0.10.x, check out the relevant tags.

License

This package is part of the Sails framework, and is free and open-source under the MIT License.

image_squidhome@2x.png

sails.io.js's People

Contributors

mikermcneil avatar sgress454 avatar luislobo avatar cxam avatar rachaelshaw avatar daedalus28 avatar acekat avatar rwoverdijk avatar natdash avatar granteagon avatar gutenye avatar larsonjj avatar jetfault avatar rmckeel avatar timofeybiryukov avatar tjwebb avatar bmac avatar

Stargazers

 avatar zjw57 avatar haastrup elijah avatar Ryan Emberling avatar Rlok avatar Kelvin Oghenerhoro Omereshone avatar  avatar Nicolas Guillen avatar  avatar Ahmed Sabry avatar Vo Anh Hoang avatar  avatar Jerico Rillo avatar Sarah D. Perea avatar yuna0x0 (edisonlee55) avatar 伊欧 avatar leeho avatar  avatar Navid Kalaei avatar  avatar Enrique Aguilar avatar Arnob avatar Gokul.J.Kurup avatar Imam Khanafi avatar Saroj Sasamal avatar Saeed avatar Jafar Rezaei avatar Rishat avatar Siro Díaz Palazón avatar  avatar Héctor pavez avatar Shivam Kaushik avatar Ali Pour Zahmatkesh avatar Qīngxiào Xuē avatar Thanh LE avatar Cainã Murtinho avatar  avatar Ziya Ibrahimli avatar Jason David Miller avatar  avatar Josh Paydon avatar Alexander Wilson avatar Ahsan Sohail avatar Josh avatar Alexander Kosianchuk avatar Aven avatar Gagan Bansal avatar Theophilus Omoregbee avatar ZY Wang avatar Lasha Kakhidze avatar Pratik avatar Josh Rowley avatar Aaron Dancer 傅子威 avatar andrii avatar  avatar Ronald Suez avatar 东方 avatar pei.shaofeng avatar star avatar Ram Thakur avatar Asier González avatar Chiyu Zhong avatar Leo Liu avatar Anabelle Handdoek avatar Owen Kellogg avatar Tyler Collier avatar Angel D. Munoz avatar Ali Sed Kashi avatar Marcel Maatkamp avatar Bhaskar Melkani avatar wanli avatar  avatar Sam Dindyal avatar Rita Zerrizuela avatar Trevor Schmitz avatar Nick Rempel avatar bhapri avatar JerryC avatar Farrukh Mamatkhalilov avatar Star Zou avatar Layton Whiteley avatar antlk avatar Ryan Wu avatar Alexander Kozhevin avatar 碎碎酱 avatar Glavin Wiechert avatar Mickael Bonfill avatar Blaine Price avatar Yuhei Yasuda avatar Tony Wang avatar Babak avatar  avatar Joshua Marquez avatar Vincent Lemeunier avatar Viacheslav Shabelnyk avatar Mikel Carozzi avatar Nazarí González avatar Austin Mao avatar StoneRen avatar Luke avatar

Watchers

Carlos Timóteo avatar  avatar  avatar James Cloos avatar Ken Snyder avatar Viacheslav Shabelnyk avatar Mike G. avatar Irl Nathan avatar Markus Padourek avatar Daniel Moore avatar Jānis avatar Eric avatar Rlok avatar Sails Bot avatar  avatar

sails.io.js's Issues

__getcookie

I tried setting up a socket connection with functional session and failed, miserably. I finally figured out why, after a full day of searching (I know how bad this makes me sound at my job, ah well).

I'm not using this lib specifically, but I found the solution and the same problem in this lib. Setting cookies from xhr cross-domain won't work. You'll need a jsonp implementation or additional script tag on the page, otherwise it will not store the cookie and your session will not persist.

var script = document.createElement('script');
script.src = xOriginCookieURL;

document.getElementsByTagName('head')[0].appendChild(script);

Now just slightly modify __getcookie to call a function and you'll know when it's done (so basic jsonp). and it's solved.

Connect to Server again if the handshake fails

I am using sails.io.js and socket.io-client on the frontend and I have configured it to reconnect if the connection is lost with the server and it is working fine. The other scenario that I want to test is mentioned below

  1. Server is down intially
  2. User accesses the frontend application in the browser
  3. The application tries to create a socket connection to the server, but the handshake fails as the server is down

How to make the socket connection in this case (i.e. try to connect until the server is up again)

Compatibility with newer versions of `socket.io`

Hello @mikermcneil and team,

Is the repo for sails.io.js library not maintained anymore?
The socket support is so outdated supporting only 2.0.3. socket.io is now at 4.x

It seems there is no maintenance here. Is there any near plans to fix this repo?

Thanks!

Issue when reconnect socket

I have a SPA which using sailjs and vuejs.
I got an issue when trying to reconect after go to a new view.
The issue is that I try to destroy all old listeners and reassign new event listener by using
io.socket.removeAllListeners();

but then I was struggling because the socket still queue old events.
Then I found out that the removeAllListeners(); methods only revoke _raw io object events but not the eventQueue object.

I managed to fix the issue by calling io.socket.eventQueue = {}.
I just wonder why the eventQueue is still remain and should I change it manually

return this;

Wrong env stored in `io.sails.environment`

Sails supports custom environments and will set sails.config.environment accordingly. However this lib will try to determine the environment (either development or production) based on whether the script src contains min or production. We do need the correct env in our frontend code.


Our current workaround is a custom API call.

No new version since 2018 ?

Dear team,

We use this sails.io.js library inside Angular web app and we was wondering if there is an issue with repository or if it has been replaced. Last version is 1.2.1 released in March 2018 embeds the outdated socket.io 2.0.3.

Any reason why this repository doesn't receive any commit anymore ?

Thanks for the clarification.

Olivier.

Cannot set io.sails.header later.

I have authorisation token in my redux store. I want to update the header once the value is available in store.
in one file i have

import socketIOClient from 'socket.io-client';
import sailsIOCLient from 'sails.io.js';
export const baseURL = 'http://localhost:1337/';

const io = sailsIOCLient(socketIOClient);
io.sails.url = baseURL;
io.sails.initialConnectionHeaders = { nosession: true };
io.sails.transports = ['websocket'];

export { io };

and in another file I want to update header

import {io} form 'xyz.js';
io.sails.header = {authorisation : '<value from store>';
io.socket.get('\url' (resp)=>{
console.log(resp)
})

the request is sent without headers;

CPU

When I include it to my Angular project, this library
cause CPU performance waste, up to 100%.

Sails/SocketIO client c#

Hello, I was wondering if there is a "sails socket io client" for C# because I develop my applications on unity. Otherwise, can we do without it?

In the sails doc:
"There are also a handful of community projects implementing Sails/Socket.IO clients for native iOS, Android, and Windows Phone."
I have not found for c#

Thank you.

[Edit]
The doc explains:

Can I bypass this client and use Socket.IO directly?

It is possible to bypass the request interpreter in your Sails app and communicate with Socket.IO directly. However, it is not reccommended, since it breaks the convention-over-configuration philosophy used elsewhere in the framework. The Sails socket client (sails.io.js) is unobtrusive: it works by wrapping the native Socket.IO client and exposing a higher-level API that takes advantage of the virtual request interpreter in Sails to send simulated HTTP requests. This makes your backend code more reusable, reduces the barrier to entry for developers new to using WebSockets/Socket.IO, and keeps your app easier to reason about.

Note: In very rare circumstances (e.g. compatibility with an existing/legacy frontend using Socket.IO directly), bypassing the request interpreter is a requirement. If you find yourself in this position, you can use the Socket.IO client, SDK, and then use sails.io on the backend to access the raw Socket.IO instance. Please embark on this road only if you have extensive experience working directly with Socket.IO, and only if you have first reviewed the internals of the sockets hook (particularly the "admin bus" implementation, a Redis integration that sits on top of @sailshq/socket.io-redis and powers Sails's multi-server support for joining/leaving rooms).

It would be really nice if there is an existing client for c#

connecting multiple clients to a single server.

I'm trying to do some testing, and it appears that I can't connect to my server multiple times on the same port. Is this a known issue? Here's my test:

function setupConnection (client) {
  var socketIoClient = require('socket.io-client');
  var sailsIoClient = require('sails.io.js');

  var io = sailsIoClient(socketIoClient);
  // Set some options:
  // (you have to specify the host and port of the Sails backend when using 
  // this library from Node.js)
  io.sails.transports = ['websocket'];
  // disable verbose logging
  io.sails.environment = 'production';
  // disable auto-connect, so that we can connect to multiple domains
  io.sails.autoConnect = false;

  return io.sails.connect('http://'+client.tenantDomain+':1338');
}


describe('Multitenancy', function () {
  var client = company1;
  it('should be able to connect to ' + client.tenantDomain, function (done) {
    var socket = setupConnection(client);
    socket.get('/date', function (body) {
      console.log("/date:", body)
      socket.disconnect();
      done();
    });
  });

  it('should be able to connect to ' + client.tenantDomain, function (done) {
    var socket = setupConnection(client);
    socket.get('/date', function (body) {
      console.log("/date:", body)
      socket.disconnect();
      done();
    });
  });

  client = company2;
  it('should be able to connect to ' + client.tenantDomain, function (done) {
    var socket = setupConnection(client);
    socket.get('/date', function (body) {
      console.log("/date:", body)
      socket.disconnect();
      done();
    });
  });

  it('should be able to connect to ' + client.tenantDomain, function (done) {
    var socket = setupConnection(client);
    socket.get('/date', function (body) {
      console.log("/date:", body)
      socket.disconnect();
      done();
    });
  });
});

for brevity I left out the definition of clients, but I hope you can see what I'm trying to do. All my tests after the first timeout, and debugging shows that the sockets are in a disconnected state.

Also, FWIW, the docs in the README.md show passing the URL as a part of the (single) options object, but it's actually the first parameter, and options are the second. tripped me up for a bit.

Issues with SameSite origin on Firefox

Because the socket session id is set as a SameSite None cookie without secure, it gets removed by Firefox.

This means this entire library does not work with current versions of Firefox when the frontend client is hosted separately from the backend sails.js framework.

Pls fix this..
Issue

io.socket.get 401 code for room connection

Hey! My old project used io.socket.get to connect to secret rooms.

io.socket.get('/list/handshake', function (data, jwr) {
if (jwr.error) {
return;
}
});

io.socket.get('/terminal/handshake', function (data, jwr) {
if (jwr.error) {
return;
}
});

After auditing the packages, I received updates and am now getting a 401 error when trying to connect.

I'm assuming that it's necessary to pass cookie bitches and the io.socket.request method is more suitable for this, but I have a poor idea of what exactly the sails require to pass the request authorization. Who faced a similar problem and what solution can work?

io.socket.request({
method: 'get',
url: '/list/handshake',
headers: {
// cookie: document.cookie,
'x-csrf-token': window.SAILS_LOCALS._csrf ? window.SAILS_LOCALS._csrf : '',
}
}, function (data, jwr) {
if (jwr.error) {
return;
}
});

io.socket.request({
method: 'get',
url: '/terminal/handshake',
}, function (data, jwr) {
if (jwr.error) {
return;
}
});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.