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

相关文章
相关标签/搜索