返回文章列表文章索引阅读全文
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 许可协议。转载请注明出处!

相关文章

2021-11-03:2021年第六届沃网安竞赛-WriteUp-MISC部分

前言 最近好久没更新博客和公众号了,有朋友问是不是在憋大招,但我不好意思说其实是因为最近一段时间太懒了,一直在当咸鱼… 意识到很久没更新这个问题,我是想写点什么的,但好像一直当咸鱼也没啥可分享的,最近刚参加了一个CTF比赛,来分享一些作为CTF小白的解题过程和思路~ 由于篇幅太长,所以本文第一篇就先只发MISC部分,相比较于固定类型的几种题目,MISC是最好玩的,比较考验知识广度和想象力~~(而且

2021-12-18 · CTF · 约 1 分钟

讨论

共 0 条

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

加载评论中…