【亲测好使】django 处理跨域问题:No 'Access-Control-Allow-Origin' header is present on the requested resource.

python django在处理跨域请求的时候,提示
Access to XMLHttpRequest at 'http://10.237.221.64:8000/api/projects/all_projects' from origin 'http://localhost:8001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

翻译过来就是: 前端在通过http://localhost:8001访问接口的时候,被CORS策略阻止

网上的解决办法都试了之后,还是不行,最后经检查,是因为django升级了版本,setting的设置有一些变化,采用如下解决办法之后,可以成功

1. 安装django-cors-headers

pip3 install django-cors-headers

2. 配置settings.py文件

INSTALLED_APPS = [
    'corsheaders',
]
# 跨域增加忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = True

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
]
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',
    'Access-Control-Allow-Origin',
)

然后启动python3 manage.py runserver 0.0.0.0:8000 ,前端重新请求,问题解决!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容