返回文章列表文章索引阅读全文
STARBLOG / 阅读手记
0_Django基础知识

Solving Cross-Origin Request Issues in Django

Several methods Use django-cors-headers for global control**(recommended)** Use JsonP, only for Get method Set response headers in views.py, can only control a single endpoint django-cors-headers First install pip install django-cors-headers Then just configure it in settings.py INSTALLED_APPS = [ ... 'corshe

曦远 (DealiAxy)约 6 分钟
目录4 个章节

Several Methods

  • Use django-cors-headers for global control (recommended)
  • Use JsonP, only works with the Get method
  • Set response headers in views.py, can only control a single endpoint

django-cors-headers

First, install

pip install django-cors-headers

Then just configure it in settings.py

INSTALLED_APPS = [
    ...
    'corsheaders',
    ...
 ] 

MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware', # 注意顺序
    ...
)
#跨域增加忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
    '*'
)

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',
)

That's it.

JsonP

When using Ajax to fetch json data, there are cross-origin restrictions. However, calling js script files on a web page is not affected by cross-origin restrictions, and JSONP takes advantage of this to achieve cross-origin transfer. Therefore, we need to change the dataType in the Ajax call from JSON to JSONP (the corresponding API also needs to support JSONP) format. JSONP can only be used for GET requests. This article will not cover this method; those who need it please search on your own

Configuring Response Headers in Views.py

Modify the implementation function of the corresponding API in views.py to allow other domains to request data via Ajax:

def myview(request): 
    response = HttpResponse(json.dumps({“key”: “value”, “key2”: “value”})) 
    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

_EOF_

Solving Cross-Origin Request Issues in Django

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…