Search code examples
javascriptajaxdjangocross-domaintwisted

Security error on attempted access to twisted rpc server from javascript in the same domain but served from different port


I have a django server that serves the basic site with user, auth etc and a twisted web server that 'should' deliver live content as json streams.

Django server is running on 127.0.0.1:8080
Twisted 127.0.0.1:9897

The problem is that when ever I try to make an http request to twisted server from a page in the django site, I get a Security Error. Apparently the same origin policy forbids this sort of communication (???) If that is the case then, are there any alternatives ? Any hints, solution .. Orbited does it successfully, any idea how ?

Thanks


Solution

  • A common workaround for this problem is to tunnel those requests through a script that acts as a proxy.

    Here is a trivial example...

    Php proxy script - proxy.php

    <?php
    echo file_get_contents(urldecode($_REQUEST['requestedUrl']));
    ?>
    

    Some nice js code that needs to make a request to the twisted server from the django site.

    // This remote request can't be made from the browser, lets forward it to the local proxy
    var twistedRequestUrl = 'http://127.0.0.1:9897/someSpecialApiCall?withAnArgument=andAnImportantValue';
    
    $.ajax({
        url : 'proxy.php?requestedUrl=' + encode(twistedRequestUrl),
        success : function(data)
        {
            alert('yay, the twisted call returned:' + data + ' yay!');
        }
    });