0

I'm developing a django system and I need to create a chat service that was in real-time. For that I used node.js and socket.io.

In order to get some information from django to node I made some ajax calls that worked very nice when every address was localhost, but now that I have deployed the system to webfaction I started to get some errors.

The djando server is on a url like this: example.com and the node server is on chat.example.com. When I make a ajax get call to django I get this error on the browser:

XMLHttpRequest cannot load http://chat.example.com/socket.io/?EIO=3&transport=polling&t=1419374305014-4. Origin http://example.com is not allowed by Access-Control-Allow-Origin.

Probably I misunderstood some concept but I'm having a hard time figuring out which one.

The snippet where I think the problem is, is this one:

socket.on('id_change', function(eu){
    sessionid = data['sessionid']

    var options = {
        host: 'http://www.example.com',
        path: '/get_username/',
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': sessionid.length
        }
    }
    var request = http.request(options, function(response) {
        response.on('data', function(msg){
            console.log('Received something')
            if(response.statusCode == 200){
                //do something here
                }
            }
        })
    })

    request.write(sessionid);
    request.end();
});

And I managed to serve socket.io.js and make connections to the node server, so this part of the setup is ok.

Thank you very much!

user2449798
  • 434
  • 1
  • 5
  • 13

1 Answers1

0

You're bumping into the cross origin resource sharing problem. See this post for more information: How does Access-Control-Allow-Origin header work?

I am NOT a Django coder at all, but from this reference page (https://docs.djangoproject.com/en/1.7/ref/request-response/#setting-header-fields) it looks like you need to do something like this in the appropriate place where you generate responses:

response = HttpResponse()
response['Access-Control-Allow-Origin'] = 'http://chat.example.com'
Community
  • 1
  • 1
HeadCode
  • 2,770
  • 1
  • 14
  • 26
  • So the response from the ajax call to django would have to contain `Access-Control-Allow-Origin: http://chat.example.com`, or the other way around? And do you have any ideia on how I would do that on django? Thanks – user2449798 Dec 24 '14 at 16:56