當使用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