drf 解决跨域
方法1
安装django-cors-headers
pip install django-cors-headers
settings
INSTALLED_APPS = [
'corsheaders',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
]
CORS_ALLOW_CREDENTIALS = True # 允许跨域时携带Cookie,默认为False
CORS_ORIGIN_ALLOW_ALL = True # 所有ip都可以访问后端接口
# CORS_ORIGIN_WHITELIST = ["http://127.0.0.1:8080",["http://192.168.10.1:8080"] # 指定能够访问后端接口的ip或域名列表
# 允许访问的请求方法
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
# 允许的headers
CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)
方法二
2.写个中间件
rom django.utils.deprecation import MiddlewareMixin
class CorsMiddleware(MiddlewareMixin):
def process_response(self, request, response):
# 任意网址
response["Access-Control-Allow-Origin"] = "*"
# 任意的请求方式
response["Access-Control-Allow-Methods"] = "*" # "PUT,DELETE,GET,POST"
# 允许任意的请求头
response["Access-Control-Allow-Headers"] = "*"
return response

浙公网安备 33010602011771号