-
-
Save vicalejuri/426829 to your computer and use it in GitHub Desktop.
import re | |
from django.utils.text import compress_string | |
from django.utils.cache import patch_vary_headers | |
from django import http | |
try: | |
import settings | |
XS_SHARING_ALLOWED_ORIGINS = settings.XS_SHARING_ALLOWED_ORIGINS | |
XS_SHARING_ALLOWED_METHODS = settings.XS_SHARING_ALLOWED_METHODS | |
except: | |
XS_SHARING_ALLOWED_ORIGINS = '*' | |
XS_SHARING_ALLOWED_METHODS = ['POST','GET','OPTIONS', 'PUT', 'DELETE'] | |
class XsSharing(object): | |
""" | |
This middleware allows cross-domain XHR using the html5 postMessage API. | |
Access-Control-Allow-Origin: http://foo.example | |
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE | |
""" | |
def process_request(self, request): | |
if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META: | |
response = http.HttpResponse() | |
response['Access-Control-Allow-Origin'] = XS_SHARING_ALLOWED_ORIGINS | |
response['Access-Control-Allow-Methods'] = ",".join( XS_SHARING_ALLOWED_METHODS ) | |
return response | |
return None | |
def process_response(self, request, response): | |
# Avoid unnecessary work | |
if response.has_header('Access-Control-Allow-Origin'): | |
return response | |
response['Access-Control-Allow-Origin'] = XS_SHARING_ALLOWED_ORIGINS | |
response['Access-Control-Allow-Methods'] = ",".join( XS_SHARING_ALLOWED_METHODS ) | |
return response |
Thanks, that's really helpful.
Quick question: What changes should I make in order to allow certain urls of my site to be "open" for cors?
I'm trying to get this going but still get this error when I load my site
XMLHttpRequest cannot load http://localhost:8080/geoserver/wfs. Origin http://127.0.0.1:8000 is not allowed by Access-Control-Allow-Origin.
My settings.py file
XS_SHARING_ALLOWED_ORIGINS = 'http://localhost:8080, http://127.0.0.1:8000/'
XS_SHARING_ALLOWED_METHODS = "POST, GET, OPTIONS, PUT, DELETE"
Any help would be greatly appreciated!
@Mbrownshoes multiple origins are not allowed. I changed XS_SHARING_ALLOWED_ORIGINS into a list and add the following code to the middleware:
if 'HTTP_ORIGIN' in request.META:
for origin in settings.XS_SHARING_ALLOWED_ORIGINS:
if origin == request.META['HTTP_ORIGIN']:
response['Access-Control-Allow-Origin'] = origin
break
It looks into the list and add the allowed-origin header only for the current origin if it is in the list.
Wonderful, thank you.
@ozen work for me , thanks !
Thanks for this! :)