Search code examples
javascriptcross-domainpubnub

Cant publish via PUBNUB. Origin is not allowed by Access-Control-Allow-Origin


Make it Using javascript API. On their site works fine, but locally cant send cross-domain request. Where is the problem?

request is XMLHttpRequest cannot load

http://pubsub.pubnub.com/publish/KEY//0/broadcast/0/%224444444444444%22.

Origin localhost:3000 is not allowed by Access-Control-Allow-Origin.


Solution

  • Using PubNub Everywhere! Even localhost and file:///

    Using PubNub on localhost is super easy! You can even use PubNub on file:/// as well.

    NOTE: always use a fixed versioned CDN in production, but pubnub-dev.js cdn is always the latest version, unminified.

    <script src=https://cdn.pubnub.com/pubnub-dev.js></script>
    <script>(function(){
    
        var pubnub = PUBNUB({
            // use your own pub/sub keys - demo keys are throttled
            publish_key   : 'demo',
            subscribe_key : 'demo',
            origin        : 'pubsub.pubnub.com',
            ssl           : true
        });
    
        pubnub.subscribe({
            channel  : 'my_channel',
            connect  : function() { /* ... CONNECTION SUCCESS ... */ },
            callback : function(message) {
                alert(message);
            }
        });
    
    })();</script>
    

    Remember to keep the origin set to pubsub.pubnub.com for all settings.