You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue+Django跨域请求CSRF Token无法读取致403错误求助

问题描述

我用Vue做前端、Django做后端开发网站,本地环境下所有请求携带CSRF Token都能正常运行;但打包发送给他人后,前后端能正常启动,所有后端请求均返回403 Forbidden错误,排查发现CSRF Token未被读取,打印值为undefined。

前端请求代码

try{
        const response = await fetch('http://127.0.0.1:8000/logout', {
            method:'POST',
            headers:{
                'Content-Type': 'application-json',
                'X-CSRFToken': Cookies.get('csrftoken'), 
            } ,
            credentials: 'include',
        })

异常环境下CSRF Token打印值

undefined

Django settings.py配置

"""
Django settings for api project.

Generated by 'django-admin startproject' using Django 5.0.1.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""

from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent



# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/


# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

MEDIA_URL = '../../frontend/src/assets/Expert_imgs/'

ALLOWED_HOSTS = ['http://127.0.0.1:5173/','127.0.0.1']
CSRF_TRUSTED_ORIGINS = ['http://127.0.0.1:5173/',' http://127.0.0.1:5173 ','http://127.0.0.1:5173']

CORS_ALLOWED_ORIGINS = ['http://127.0.0.1:5173 ' ,'http://localhost', 'http://127.0.0.1:5173',  'http://localhost:5173','http://127.0.0.1:5173']
CORS_ALLOW_CREDENTIALS = True

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'ace.it.notify@gmail.com'

SESSION_COOKIE_AGE = 600

LOGIN_URL= 'http://127.0.0.1:5173/'
LOGOUT_REDIRECT_URL = 'http://127.0.0.1:5173/'

# Application definition

INSTALLED_APPS = [
    'AceIt',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
]
AUTH_USER_MODEL = "auth.User"

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',
]

ROOT_URLCONF = 'api.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            BASE_DIR / 'templates',
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'api.wsgi.application'


# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
解决方案
  • 修复Cookie依赖与读取问题
    先确认前端是否正确安装了js-cookie库,对方环境可能缺少这个依赖。执行npm install js-cookie安装后,在代码里正确导入:

    import Cookies from 'js-cookie'
    

    同时在Django的settings.py里添加Cookie跨域配置,确保前端能读取到CSRF Cookie:

    CSRF_COOKIE_SAMESITE = 'Lax'
    CSRF_COOKIE_DOMAIN = '127.0.0.1'
    
  • 修正请求头Content-Type
    代码里的application-json是错误的MIME类型,正确写法是application/json,格式错误会导致Django无法正确处理请求,进而影响CSRF验证:

    headers:{
        'Content-Type': 'application/json',
        'X-CSRFToken': Cookies.get('csrftoken'), 
    }
    
  • 清理冗余的域名配置
    你的CSRF_TRUSTED_ORIGINS和CORS_ALLOWED_ORIGINS里有重复域名和多余空格,会导致域名匹配失败,改成简洁的配置:

    CSRF_TRUSTED_ORIGINS = ['http://127.0.0.1:5173']
    CORS_ALLOWED_ORIGINS = ['http://127.0.0.1:5173', 'http://localhost:5173']
    ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
    
  • 确保Django正确返回CSRF Token
    可以在Django里新增一个视图专门返回CSRF Token,前端调用后直接使用:

    from django.middleware.csrf import get_token
    from django.http import JsonResponse
    
    def get_csrf_token(request):
        csrf_token = get_token(request)
        return JsonResponse({'csrfToken': csrf_token})
    

    前端请求这个接口获取Token后,存入Cookie或直接放在请求头里。

  • 显式设置CSRF Cookie路径
    在settings.py里添加以下配置,确保Cookie路径正确:

    CSRF_COOKIE_PATH = '/'
    

内容的提问来源于stack exchange,提问作者codeouz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 05:41:01