0

We are using AngularJS and Django frontend and backend respectively. We are facing CORS error as we added corsheaders in installed_app and also added middlewares still we are facing the same problem

We are using AngularJS v1.6.3, Django 1.10.11 and Python 2.7.

Angular Controller:

var socket = io.connect('http://192.168.13.129:8000/');

socket.on('connect', function (data) { 
    console.log('connected') 
})

in django settings.py

INSTALLED_APPS = (
    'corsheaders',
)



MIDDLEWARE = [ 
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]

CORS_ORIGIN_ALLOW_ALL=True

The expected result is Socket.IO CORS request to be done successfully, but we are getting following error:

Access to XMLHttpRequest at 'http://192.168.13.129:8000/socket.io/?EIO=3&transport=polling&t=MncX14t' from origin 'http://192.168.13.148:8082' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

jasie
  • 2,192
  • 10
  • 39
  • 54
Aditya
  • 51
  • 1
  • 6
  • Please help me as soon as possible to solve this problem. Thanks – Aditya Aug 06 '19 at 12:30
  • hi all, i have solved this problem by adding cors setting in view.py along with above mentioned steps in question. Before sio = socketio.Server(async_mode=async_mode) After sio = socketio.Server(async_mode=async_mode, cors_allowed_origins="*") – Aditya Aug 07 '19 at 06:19

1 Answers1

2

The quick and dirty solution that a lot of people go to with CORS is to disable it by allowing all origins. But this opens the doors to vulnerabilities such as CSRF attacks against your users.

In your case, what I recommend that you do is that you enable only the origin(s) from where you expect to receive requests. From your example, the correct and secure Socket.IO configuration you'd want to use is this:

sio = socketio.Server(cors_allowed_origins="http://192.168.13.148:8082")

And if you have additional origins, just make the above argument a list and add all your origins there. A * is okay for internal tests, but not a good idea for a production site unless you really know what you are doing.

Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152