我正在写一个网站,使用Vue作为前端框架,django作为后端框架。我已将 csrf 令牌包含在从前端到后端的每个请求中,以确保不会收到 403 Forbidden 错误。所有请求都正常并且功能正常。现在这里是事情不起作用的地方。我将代码作为压缩文件发送给其他人以供他们运行。前端和后端都运行没有问题,只是无法执行对后端的请求。每个请求都会返回 403 Forbidden 错误,这是因为请求中未包含 csrf 令牌。请记住,这是相同的代码,可以在一台笔记本电脑上运行,但不能在另一台笔记本电脑上运行。我可以做什么来解决这个问题?
前端到后端的请求:
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 令牌时的值:
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 = '[email protected]'
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'
如有任何帮助,我们将不胜感激
问题最终是在一台笔记本电脑上,前端在 127.0.0.1 上运行,而在另一台笔记本电脑上则在 localhost 上运行。这导致 csrf 令牌被设置在一个域上,该域是后端的 127.0.0.1,我试图从本地主机读取它。我只需要将其添加到我的 vite.config 文件中,以确保前端与后端在同一域上运行:
server: {
host: '127.0.0.1'
}