在经过 simplejwt 身份验证的网页上发生 Cors 错误

Cors error happening on a simplejwt authenticated webpage

我在我的代码中使用了 simplejwt,我还在我的项目中添加了 django-cors-headers 以允许前端开发。问题是我有 2 个 API 需要身份验证才能允许用户使用它们,我无法在前端向这两个 API 发送请求,我收到以下错误:

Access to fetch at 'http://localhost:8000/api/user/myapi' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field x-auth-token is not allowed by Access-Coontrol-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',
    'rest_framework.authtoken',
    'rest_framework_simplejwt',
    'corsheaders',
    ...
]

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

ALLOWED_HOSTS=['*']
CORS_ORIGIN_ALLOW_ALL = True

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),  
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10,
}

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=10),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=10),
    'ROTATE_REFRESH_TOKENS': True,
    'BLACKLIST_AFTER_ROTATION': False,
    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'VERIFYING_KEY': None,
    'AUTH_HEADER_TYPES': ('JWT',),
    'USER_ID_FIELD': 'userID',
    'USER_ID_CLAIM': 'user_id',
    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',
}

这是我的 views.py 和 serializers.py

# Serializers.py
class myAPISerializer(serializers.ModelSerializer):
    class Meta:
        model = someModel
        fields = ('user', 'someField',)
        read_only_fields = ('user',)

    def create(self, validated_data):
        ... #Some changes
        return super().create(validated_data)

# Views.py
class PaymentView(generics.CreateAPIView):
    serializer_class = PaymentSerializer

    def get_queryset(self):
        return Payment.objects.all()

根据 django-cors-headers 文档:

CorsMiddleware should be placed as high as possible, especially before any middleware that can generate responses such as Django’s CommonMiddleware or Whitenoise’s WhiteNoiseMiddleware. If it is not before, it will not be able to add the CORS headers to these responses.

所以只需将它添加到您的列表顶部,如下所示:

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