前后端协作开发得时候确实,开发本身这件事情会让跨域有风险,但是远程协作 或者让开发这件事情更加得模块化,或者解耦得话 是需要跨域得操作的
1.安装corsheaders中间件:
pip install django-cors-headers
2.设置python文件中得seting文件
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app1.apps.App1Config',
'API.apps.ApiConfig',
# 让开发得API接口允许跨域
'corsheaders',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
#引入跨域设置开始
'corsheaders.middleware.CorsMiddleware',
# 引入跨域设置结束
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
3.前端ajx接受接口得写法
#跨域设置
CORS_ALLOW_ALL_ORIGINS = True
CORS_ORIGIN_ALLOW_ALL =True
CORS_ALLOW_HEADERS=('*')
import { userService} from '../api/user'
let user=ref('')
userService({
methon: 'GET',
url: '/api/responseJson',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json',
}
}).then((res) => {
user.value=res.data
}).catch((error) => {
console.error = (msg, ...optionalParams) => { // 重写 console.error
console.log(msg, ...optionalParams); // 打印到console的信息正常显示
return false; // 返回false,使得控制台不会显示红色错误
};
console.error('用户接口请求失败:', error);
})
如果要post还等增 权限
这个错误信息表明您的前端应用(位于 http://localhost:5173)试图访问后端API(/app/edituser/),但是后端服务器拒绝了该请求,因为它没有将 http://localhost:5173 列为受信任的来源(trusted origin)。这通常是由于跨域资源共享(CORS)配置不当导致的。 要解决这个问题,您需要在后端服务器上配置CORS策略,以允许来自 http://localhost:5173 的请求。如果您使用的是Django,您可以通过安装并配置django-cors-headers这个第三方包来实现这一点。 以下是解决这个问题的步骤: 安装 django-cors-headers: 首先,您需要在您的Django项目中安装django-cors-headers。您可以使用pip来安装它: bash复制代码
| pip install django-cors-headers |
添加 corsheaders 到 INSTALLED_APPS: 打开您的settings.py文件,并在INSTALLED_APPS列表中添加corsheaders: python复制代码
| INSTALLED_APPS = [ |
| # ... |
| 'corsheaders', |
| # ... |
| ] |
配置CORS中间件: 在settings.py中,找到MIDDLEWARE设置,并添加corsheaders.middleware.CorsMiddleware到中间件列表的顶部: python复制代码
| MIDDLEWARE = [ |
| 'corsheaders.middleware.CorsMiddleware', |
| # ... |
| ] |
配置CORS策略: 您可以在settings.py中配置CORS策略,允许来自特定来源的请求。例如,要允许来自http://localhost:5173的请求,您可以添加以下配置: python复制代码
| CORS_ALLOW_ALL_ORIGINS = False |
| CORS_ORIGIN_ALLOW_LIST = [ |
| 'http://localhost:5173', |
| ] |
| CORS_ALLOW_METHODS = [ |
| 'DELETE', |
| 'GET', |
| 'OPTIONS', |
| 'PATCH', |
| 'POST', |
| 'PUT', |
| ] |
| CORS_ALLOW_HEADERS = [ |
| 'accept', |
| 'accept-encoding', |
| 'authorization', |
| 'content-type', |
| 'dnt', |
| 'origin', |
| 'user-agent', |
| 'x-csrftoken', |
| 'x-requested-with', |
| ] |
重启开发服务器: 保存settings.py文件并重启您的Django开发服务器,以使CORS配置生效。
现在,当您从http://localhost:5173发送请求到/app/edituser/时,服务器应该不再返回403 Forbidden错误,而是根据请求的具体情况返回相应的响应。 请注意,如果您在生产环境中部署Django应用,您应该仔细考虑CORS配置的安全性,确保只允许受信任的源进行访问。在上面的示例中,我们允许了http://localhost:5173,这通常适用于开发环境。在生产环境中,您应该限制允许的来源,并可能需要添加其他安全机制,如身份验证和授权。
跨域参考样板"""
Django settings for djangoProject project.
Generated by 'django-admin startproject' using Django 5.0.4.
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: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-j1c!2z%8bldcbl@7(^a@*b9qyx6o710t_%14bgdk6056ef7tv_'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
# 让开发得API接口允许跨域
'corsheaders',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app.apps.AppConfig',
]
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_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_METHODS = [
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_HEADERS = [
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
]
ROOT_URLCONF = 'djangoProject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': []
,
'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 = 'djangoProject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
"NAME": "mapback",
"USER": "root",
"PASSWORD": "123456",
"HOST": "127.0.0.1",
"PORT": "3306",
}
}
# 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 = 'zh-hans'
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'
|