繁体   English   中英

使用 Axios 从前端访问 Django Rest API 时出现 Cors 错误

[英]Cors error when accessing Django Rest API from front end Using Axios

使用 axios 访问 django Rest API 出现以下错误

从源“ http://localhost:8080 ”访问“ http://api.localhost:8080/auth/register-shop/ ”的 XMLHttpRequest 已被 CORS 策略阻止:请求标头字段 access-control-allow-origin预检响应中的 Access-Control-Allow-Headers 不允许。

我在此链接中提到了 django cors 标头https://pypi.org/project/django-cors-headers/

前端页面

 axios({
                                method: 'post',
                                url: 'http://api.localhost:8080/auth/register-shop/',
                                //url: 'http://api.yuniq.ml/auth/register-shop/',

                                headers: {
                                        "Access-Control-Allow-Origin": "*",
                                        "content-type": "application/json"
                                },
                                data: {

                                        "name": Name,
                                        "address": Address,
                                        "city": City,
                                        "postalC ode": PostalCode,
                                        "telephone": Telephone,
                                        "openTime": Opentime,
                                        "closeTime": Closetime,
                                        "image_url": Image_url  //still not working 

                                }
                        }).then(function (response) {
                                console.log(response);
                        })
                                .catch(function (error) {
                                        console.log(error);
                                });


                }

设置.py

INSTALLED_APPS = ['corsheaders']


MIDDLEWARE = [

    'django_hosts.middleware.HostsRequestMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware' , #add cors middleware
    'django.middleware.common.CommonMiddleware',
    'corsheaders.middleware.CorsPostCsrfMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django_hosts.middleware.HostsResponseMiddleware',
]



CORS_ORIGIN_ALLOW_ALL = True

执行此操作后错误未解决

我遇到了同样的问题并执行了以下步骤:

  • 我检查了从 Axios 发送的标头。
  • 确保安装了这个包

'pip 安装 django-cors-headers'

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

MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    ...
]

现在有两个选择:

1 - 只需在 settings.py 中添加以下变量即可允许访问所有域:

ALLOWED_HOSTS=['*']

CORS_ORIGIN_ALLOW_ALL = 真

2 - 不允许访问所有域,但允许访问您正在使用 API 的域。 在settings.py中添加以下变量

ALLOWED_HOSTS=['http://localhost:5000']

CORS_ORIGIN_ALLOW_ALL = 假

CORS_ORIGIN_WHITELIST = ('http://localhost:5000',)

如果您想随请求发送特定标头,您也可以在 setting.py 中定义允许听者。

CORS_ORIGIN_ALLOW_ALL = 真

CORS_ALLOW_HEADERS = [   
    ...
    'Currency',
    ...
 ]

检查这可以帮助您:

https://dzone.com/articles/how-to-fix-django-cors-error

我最近遇到了同样的问题,我已经解决了。 我还使用corsheaders来避免 CORS 错误,并且在我引入Authentication之前它工作正常。 对于那些权限设置为IsAuthenticated api,同样的问题再次开始。 所以我在 settings.py 中的ALLOWED_HOSTS列表中添加了某个主机,并且它起作用了。 添加主机有两种选择。

选项 1. ALLOWED_HOSTS=["*"]

选项 2. ALLOWED_HOSTS=['your host1', 'your host2', 'your host3', ......]

注意:我不喜欢选项 1,因为它会引起安全问题。 所以选择选项2。

您的 axios 请求不应包含此标头: "Access-Control-Allow-Origin": "*",

这应该只包含在服务器的响应中。 尝试从您的 axios 请求中删除它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM