简体   繁体   中英

Access-Control-Allow-Origin using ShareJS

I have my website on one domain/server: www.mysite.com and I'm running ShareJS on another server: www.my-other-server.com:8000.

www.mysite.com/index.html

<script src="http://www.my-other-server.com:8000/bcsocket.js"></script>
<script src="http://www.my-other-server.com:8000/share.js"></script>
<script src="http://www.my-other-server.com:8000/textarea.js"></script>

...

<textarea id='sharetext' ></textarea>

<script>
    // get the textarea element
    var elem = document.getElementById("sharetext");

    // connect to the server
    var options = {
        origin: "www.my-other-server.com:8000",
        browserChannel:{cors:"*"}
    }

    var connection = sharejs.open('test', 'text', options, function(error, doc) {
      doc.attach_textarea(elem);
  });

</script>

I get the following error in the JS console:

XMLHttpRequest cannot load http://www.my-other-server.com:8000/test?VER=8&MODE=init&zx=v44znr3caqea&t=1. Origin http://www.mysite.com is not allowed by Access-Control-Allow-Origin. 

This ShareJS GitHub Issue ( https://github.com/share/ShareJS/issues/77 ) suggests adding browserChannel:{cors:"*"} to the share options, as I did above, but it did not seem to have any effect...

What do I do here? It's important that my sharejs traffic is on a separate server than my static/dynamic web server.

On server side in node.js, if you are using express.js you need to add extra headers, that will allow cross-domain traffic from server side:

app.configure(function() {
  app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
    next();
  });
  app.set('jsonp callback', true);
});

On client side you still might end up with security issues, so it is even better to use JSONP, so from server side response like that:

res.jsonp({ hello: 'world' });

And on client side AJAX like that:

$.ajax({
  url: "www.my-other-server.com:8000",
  type: 'GET',
  dataType: 'jsonp',
  success: function(data) {
    console.log(data)
  },
  error: function(xhr, status, error) {
    console.log('error[' + status + '] jsonp');
  }
});

Try adding browserChannel: { cors:"*" } in bin/options.js. It should work.

The final options.js may look like this

// ShareJS options
module.exports = {
    // Port to listen on
    port: 8000,

    // Database options
    db: {
        // DB type. Options are 'redis', 'couchdb' or 'none'. 'redis' requires the
        // redis npm package.
    //
    // If you don't want a database, you can also say db: null. With no database,
    // all documents are deleted when the server restarts.

    // By default, sharejs tries to use the redis DB backend.
        type: 'redis',

        // The prefix for database entries
        prefix: 'ShareJS:',

        // The hostname, port and options to pass to redis.
        // null lets the database decide - redis by default connects to localhost port 6379.
        //hostname: null,
        //port: null,
        //redisOptions: null


        // To use CouchDB uncomment this section then run bin/setup_couch.
    // Database URI Defaults to http://localhost:5984/sharejs .
        //type: 'couchdb',
        //uri: "http://admin:admin@localhost:5984/ot",


    // To use postgresql uncomment this section then run bin/setup_pg
    //type: 'pg',
    //uri: 'tcp://josephg:@localhost/postgres',

    // By default, sharejs will create its tables in a schema called 'sharejs'.
    //schema: 'sharejs',
    //operations_table: 'ops',
    //snapshot_table: 'snapshots',

    // sharejs will automatically try and create the DB tables if they don't exist. You
    // can create the database tables manually using bin/setup_pg.
    //create_tables_automatically: true,
    },

    // The server will statically host webclient/ directory at /share/*.
    // (Eg, the web client can be found at /share/share.js).
    // Set staticpath: null to disable.
    staticpath: '/share',

    // REST frontend options. Set rest: null to disable REST frontend.
    rest: {
    },

    // SocketIO frontend options. Set socketio: null to disable socketIO frontend.
    socketio: {
      // Specify tuples for io.configure:
      // 'transports': ['xhr-polling', 'flashsocket']
    },

  // Browserchannel server options. Set browserChannel:null to disable browserchannel.
   browserChannel: {cors:"*"},

    // Authentication code to test if clients are allowed to perform different actions.
    // See documentation for details.
    //auth: function(client, action) {
    //  action.allow();
    //}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM