Django 跨域問題


當使用Django 做接口時,被html5 或者app訪問時 存在跨域問題 導致無法請求到數據,具體解決辦法如下;

跨域問題解決 安裝pip install django-cors-headers
修改Django下setting.py

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

MIDDLEWARE = (
    ...
    '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',
)
 
        

測試html代碼

<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
    function copyText(){ $.ajax({ type: 'GET', dataType:'jsonp', jsonp:"callback", url: 'http://127.0.0.1:8000/hello', success: function (data) { console.log(data) }, error: function () { console.log("有問題1111") } }); } </script> <button onclick="copyText()">復制文本</button>

當ajax采用jsonp時 需要用以下調用方式
from django.http import HttpResponse
import  json
def hello(request):
    callback = request.GET['callback']
    response = HttpResponse('{0}({1})'.format(callback,json.dumps({"key":"value"})))
    return  response

或者報 SyntaxError: unexpected token: ':' 或者 SyntaxError: missing ; before statement


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM