使用ShareJS的Access-Control-Allow-Origin

时间:2013-07-01 06:16:59

标签: javascript apache node.js share.js

我的网站位于一个域/服务器上:www.mysite.com,我在另一台服务器上运行ShareJS: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>

我在JS控制台中收到以下错误:

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. 

这个ShareJS GitHub问题(https://github.com/share/ShareJS/issues/77)建议将browserChannel:{cors:"*"}添加到share选项中,就像我上面所做的那样,但它似乎没有任何影响...

我在这做什么?重要的是我的sharejs流量位于与静态/动态Web服务器不同的服务器上。

2 个答案:

答案 0 :(得分:0)

在node.js的服务器端,如果您使用的是express.js,则需要添加额外的标头,这将允许来自服务器端的跨域流量:

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);
});

在客户端,你可能最终会遇到安全问题,因此使用JSONP会更好,所以从服务器端响应就是这样:

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

在客户端这样的AJAX:

$.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');
  }
});

答案 1 :(得分:0)

尝试在bin / options.js中添加browserChannel: { cors:"*" }。它应该工作。

最终的options.js可能看起来像这样

// 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();
    //}
}