Django 跨域問題

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

跨域問題解決 安裝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代碼css

<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 statementhtml

相關文章
相關標籤/搜索