📂drf
🔖跨域
2022-10-27 16:49阅读: 70评论: 0推荐: 0

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

本文作者:Sherwin

本文链接:https://www.cnblogs.com/sherwin1995/p/16832830.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Sherwin_szw  阅读(70)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
  1. 1 404 not found REOL
404 not found - REOL
00:00 / 00:00
An audio error has occurred.