2013-07-01 1 views
2

У меня есть мой сайт на одном домене/сервере: www.mysite.com, и я запускаю ShareJS на другом сервере: www.my-other-server.com:8000.Access-Control-Allow-Origin с использованием ShareJS

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-трафик находился на отдельном сервере, чем мой статический/динамический веб-сервер.

ответ

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

Попробуйте добавить browserChannel: { cors:"*" } в корзину/options.js. Он должен работать.

Окончательный 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:[email protected]: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(); 
    //} 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^