python(Django)解决跨域的两种方式

python(Django)解决跨域的两种方式

方式一:

json序列化+响应参数

def new(request):
	 data_list = {'username':'xiaoming', 'age':18, 'gender':1}
	 response = HttpResponse(json.dumps([data_list]))
	 response['Access-Control-Allow-Origin'] = '*'  #  其实加这一个响应参数就行
	 response['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
	 response['Access-Control-Max-Age'] = '1000'
	 response['Access-Control-Allow-Headers'] = '*'
	 return response

方式二

参考官方文档

  1. 安装模块
pip install django-cors-headers
  1. settings配置
INSTALLED_APPS  =  [ 
    ... 
    'corsheaders'... 
]

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

"""
跨域设置
"""
#  参考   https://pypi.org/project/django-cors-headers/
"""
三者设置其一即可
"""
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOWED_ORIGINS = [
    "https://example.com",
    "https://sub.example.com",
    "http://localhost:8000",
    "http://127.0.0.1:8000"
]

"""
以下可以不要
"""
CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)

CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'Pragma',
)


  1. 直接返回json
def new(request):
	 data_list = {'username':'xiaoming', 'age':18, 'gender':1}
	 response = HttpResponse(json.dumps([data_list]))
	 return response

你可能感兴趣的:(python,python,django,json)