• Stars
    star
    182
  • Rank 211,154 (Top 5 %)
  • Language
    JavaScript
  • Created over 10 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Browser SDK for communicating w/ Sails via sockets

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

More Repositories

1

sails

Realtime MVC Framework for Node.js
JavaScript
22,811
star
2

waterline

An adapter-based ORM for Node.js with support for mysql, mongo, postgres, mssql (SQL Server), and more
JavaScript
5,412
star
3

sails-docs

**Latest docs now live in the Sails core repo!** The source markdown files for the official Sails.js documentation, which gets compiled, squeezed, and stretched into HTML when we deploy the Sails website.
778
star
4

waterline-docs

WARNING: The content in this repo is out of date! See https://github.com/balderdashy/sails-docs for the most up-to-date documentation
452
star
5

sails-mongo

MongoDB adapter for Sails.js / Waterline ORM.
JavaScript
411
star
6

sails-mysql

MySQL adapter for Sails.js/Waterline
JavaScript
193
star
7

angularSails

AngularJS bindings for Sails. http://angularjs.org
JavaScript
184
star
8

sails-postgresql

PostgreSQL adapter for Sails.js
JavaScript
167
star
9

sails-redis

Lightweight Redis adapter for Node.js/Sails apps, focused on providing easy direct access to the configured, connected, ready-to-use Redis client instance. (Useful for caching.)
JavaScript
129
star
10

seed

A sample application generated by Sails.
JavaScript
91
star
11

mast

UI conventions built on top of Backbone.JS
JavaScript
81
star
12

sails-hook-email

Sails email hook
JavaScript
67
star
13

backbone-to-sails

Backbone SDK for communicating with Sails.js over Socket.io
JavaScript
64
star
14

skipper-s3

Streaming file uploads to S3
JavaScript
62
star
15

include-all

An easy way to include all files within a directory. Note: This is a fork of felixge's require-all which allows for optional includes.
JavaScript
56
star
16

sails-adapter-boilerplate

Example of a custom adapter (i.e. ORM plugin) for Waterline / Sails.js
JavaScript
45
star
17

sails-disk

Development-only persistent adapter for Sails.js / Waterline
JavaScript
44
star
18

captains-log

Lightweight logger with a simple pass-through configuration for use with fancier logging libraries. Used by the Sails framework. Optional support for colorized output, custom prefixes, and log levels (using npm's logging conventions.)
JavaScript
44
star
19

waterline-schema

This is the core schema builder used in the Waterline ORM.
JavaScript
33
star
20

activity-overlord-2-preview

A preview of Irl Nathan's Activity Overlord 2.0 (complete tutorial of Sails w/ Angular 1)
JavaScript
31
star
21

sails-generate

Master of ceremonies for generators in the Sails CLI
JavaScript
28
star
22

sails-generate-frontend

Generate the frontend part of a new Sails app.
JavaScript
26
star
23

sails-memory

In-memory, non-persistent adapter for Sails.js / Waterline
JavaScript
24
star
24

sails-hook-sockets

Implements socket.io support in Sails.
JavaScript
23
star
25

sails-hook-dev

A Sails hook that provides diagnostic / debugging information and levers during development.
JavaScript
22
star
26

sails-angular-seed

Boilerplate AngularJS app with Sails
JavaScript
21
star
27

enpeem

Lightweight wrapper for accessing npm programmatically (alternative to adding `npm` as a dependency)
JavaScript
19
star
28

sails-hook-orm

Implements support for Waterline ORM in Sails.
JavaScript
18
star
29

sails-hook-subapps

Sails hook for including child Sails apps into a parent app
JavaScript
18
star
30

sails-generate-generator

Generate a custom generator for Sails.js
JavaScript
18
star
31

merge-defaults

A recursive version of `_.defaults`.
JavaScript
16
star
32

waterline-adapter-tests

API integration tests for Waterline adapters
JavaScript
16
star
33

waterline-sequel

A SQL generator for use in Waterline Adapters
JavaScript
16
star
34

skipper-disk

Streaming file uploads to a server's local filesystem
JavaScript
14
star
35

sails-twitter

Twitter adapter for Sails.js
JavaScript
14
star
36

waterline-criteria

Utility library for use in Sails adapters where you need to filter a list of output using a criteria object
JavaScript
13
star
37

sails-generate-views-jade

Generate default views for a Sails app using Jade templates
HTML
11
star
38

billable

Tracks billable hours.
JavaScript
10
star
39

sails-generate-adapter

Generate a waterline/sails.js adapter.
JavaScript
10
star
40

fixture-stdout

A test fixture to intercept writes to stdout.
9
star
41

sails-generate-backend

Generate the backend part of a new Sails app.
JavaScript
9
star
42

sails-generate-new

Generate a new Sails app.
JavaScript
8
star
43

sails-riak

Riak adapter for Sails.js
CoffeeScript
7
star
44

machinepack-youtube

Communicate with the Youtube API to get video views, etc.
JavaScript
6
star
45

deretina

For supporting retina displays on the web: downsizes @2x images in the current directory
JavaScript
6
star
46

example-sails-proj-with-angular

JavaScript
6
star
47

sails-irc

IRC adapter for Sails.js
JavaScript
6
star
48

sails-generate-model

Generate a model in a Sails app.
JavaScript
5
star
49

sails-build-dictionary

DEPRECATED in Sails v1.0 (instead, just use [email protected] directly)
JavaScript
5
star
50

machinepack-slack

Use the Slack API from Node.js.
JavaScript
5
star
51

alcohol

Makes your dates prettier
4
star
52

sails-generate-api

API generator for Sails
JavaScript
4
star
53

booty

CoffeeScript
4
star
54

sails-util

Shared utilities between sails, waterline, etc.
JavaScript
4
star
55

sails-dirty

Sails.js adapter for @felixge's node-dirty
JavaScript
3
star
56

sails-elastic-search

Elastic Search Adapter for Sails JS
3
star
57

htassets

A mobile-compatible makeover for the default apache directory listing
JavaScript
3
star
58

Mobile-HTML-5-Video-Example

Cross-platform mobile video player using HTML 5
3
star
59

express-with-shared-mongo-session-example

An example of using a shared session in Express with MongoDB as the storage container
JavaScript
2
star
60

sails-generate-views

Generate default views for a Sails app
HTML
2
star
61

dev-workshop-conf

JavaScript
2
star
62

UserSwarm

JavaScript
2
star
63

sails-generate-controller

Generate a new controller file in an existing Sails app.
JavaScript
2
star
64

sails-generate-sails.io.js

Generate a sails.io.js browser SDK file at ./assets/js/dependencies/sails.io.js.
JavaScript
2
star
65

skipper-adapter-tests

Generic acceptance tests for Skipper adapters
JavaScript
1
star
66

waterline-cursor

Association/subquery helper
JavaScript
1
star
67

sails-generate-gruntfile

Generate gruntfile for a sails app.
JavaScript
1
star
68

stubble

A trimmed-down mustache.js for jQuery
JavaScript
1
star
69

sails-generate-hook

Generate a custom hook for Sails.js.
JavaScript
1
star
70

Naked

Chrome extension that opens links with stylesheets disabled for privacy.
1
star
71

sails-stringfile

translated/localized stringfiles containing messages from Sails core and dependencies
JavaScript
1
star
72

blueprint-api-example

An example of a Sails app using a blueprint API for use in "Run in Postman" buttons on the Sails website.
JavaScript
1
star
73

waterline-blob

Factory which generates waterline adapter definitions from blob definitions (eventually merge into waterline core)
JavaScript
1
star