React Django CORS无法正常运作:已被CORS政策封锁

时间:2020-02-12 15:50:12

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

我已经尝试了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)
    });
}

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

仅尝试前端的内容类型,

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)
    });
}

答案 1 :(得分:0)

首先,从 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)
    });

然后,它会起作用。