【问题标题】:React Django CORS not working : has been blocked by CORS policyReact Django CORS 不工作:已被 CORS 策略阻止
【发布时间】:2020-05-28 05:42:06
【问题描述】:

我已经尝试了 react 和 django api 之间所有可能的 CORS 组合。 还是不行。

我遇到了这个错误

 has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
    'todos'
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = False

view.py

class StuffViewSet(APIView):

    def post(self, request):
        serializer = StuffSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(data = "data saved", status=status.HTTP_201_CREATED)
        return Response(data = "data not saved", status=status.HTTP_400_BAD_REQUEST)

    def get(self, request):
        snippets = Stuff.objects.all()
        serializer = StuffSerializer(snippets, many=True)
        return Response(data = json.dumps(serializer.data))

我是从这样的反应中调用 api

getAPI(e) {
    const headers = {
        'Content-Type': 'application/json',
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET,OPTIONS,POST,PUT"
    }
    axios.get('http://localhost:8000/api', {
        headers: headers
        }).then(function(response) {
            console.log("/api")
            console.log(response.data)
    });
}

我在这里做错了什么?

【问题讨论】:

  • 没有理由将 Access-Control-Allow-* 标头设置为请求标头——因为它们是响应标头,而不是请求标头。也许你应该试试这个pypi.org/project/Flask-Cors
  • 在您的 fetch 或 axios 请求中添加 cors:"no-cors"。
  • @EddwinPaz 你有这个例子吗?

标签: python django reactjs cors django-cors-headers


【解决方案1】:

如果 corsheaders 和verything 设置正确, 请试试这个

axios.get('your-api', {headers: { 'Accept': 'application/json' }}).then(res => console.log(res.data).catch(err => alert(err))

这对我有用,也可能对其他人有用并让他们免于沮丧。

【讨论】:

    【解决方案2】:

    总结解决方案:

    从您的请求标头中删除 "Access-Control-Allow-Origin": "*"

    我在这里遇到了同样的问题。我花了几个小时来修复它。

    我没看清楚消息控制台。

    很清楚:

    请求头域 access-control-allow-origin 不允许 预检响应中的 Access-Control-Allow-Headers。

    CORS 预检请求是一种 CORS 请求,用于检查 CORS 协议是否被理解以及服务器是否使用特定的方法和标头知道。 (https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request)

    因此,如您所见,您的服务器不允许使用 Access-control-allow-headers。

    【讨论】:

      【解决方案3】:

      首先,从 API 调用中删除标头。 其次,将 http://localhost:8000/api 改为 http://localhost:8000/api/。 代码将是:

      axios.get('http://localhost:8000/api/')
           .then(function(response) {
                  console.log("/api")
                  console.log(response.data)
          });
      

      然后,它会工作。

      【讨论】:

        【解决方案4】:

        只尝试前端的内容类型,

        getAPI(e) {
            const headers = {
                'Content-Type': 'application/json'
            }
            axios.get('http://localhost:8000/api', {
                headers: headers
                }).then(function(response) {
                    console.log("/api")
                    console.log(response.data)
            });
        }
        

        【讨论】:

        • 运气不好。使用“Access-Control-Allow-Origin”:“*”,至少 Django 响应为 [12/Feb/2020 15:35:17]“OPTIONS /api HTTP/1.1”200 0
        • 我的配置完全相同,对我来说工作正常。
        • 标头:{ 'Access-Control-Allow-Origin': '*', }
        猜你喜欢
        • 2021-01-07
        • 1970-01-01
        • 1970-01-01
        • 2020-08-27
        • 1970-01-01
        • 2023-01-14
        • 2020-08-29
        • 2021-04-24
        • 2021-12-25
        相关资源
        最近更新 更多