python - 对 Django CORS 问题使用react

标签 python reactjs django python-3.9

错误详情
enter image description here
单击按钮时生成了两个请求。
到目前为止我搜索了什么?
Axios blocked by CORS policy with Django REST Framework
CORS issue with react and django-rest-framework
但无济于事
我在做什么?
将 POST 请求从 react 提交到 DJango API
Django 端设置文件

CORS_ORIGIN_ALLOW_ALL = True
ALLOWED_HOSTS = [
    "http://127.0.0.1:3000", 
    "http://127.0.0.1", 
    "http://localhost:3000", 
    "http://localhost"
]
CORS_ORIGIN_WHITELIST = [
    "http://127.0.0.1:3000", 
    "http://127.0.0.1", 
    "http://localhost:3000", 
    "http://localhost"
]

INSTALLED_APPS = [
    ......,
    "corsheaders"
]

MIDDLEWARE = [
    .........,
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]
响应 axios 请求
function authenticate() {
    let body = {
        "email": "ac",
        "password": "def"
    };
    const headers = {
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json',
    }

    axios.post("http://127.0.0.1:8000/login/", body, {
        headers: headers
    })
    .then(function(response) {
        console.log(response.data);
    })
    .catch(function(error) {
        console.log(error);
    });
}
尝试使用 fetch 的另一种方法,但无济于事
function authenticate() {
    let body = {
        "email": "hi",
        "password": "pass"
    };
    const headers = {
        'Content-Type': 'application/json',
    }
    fetch("http://127.0.0.1:8000/login", {
        method: "POST", 
        headers: { 
            "Content-Type": "application/json"
        },
        body: JSON.stringify(body)
    })
    .then(function(response) {
        console.log(response.data);
    })
    .catch(function(error) {
        console.log(error);
    });
}
DJango 边法
def Login(request):
    if(request.method == "POST"):
        return JsonResponse({"message" : "Invalid credentials"}, status=401)

最佳答案

以下设置对我有用

CORS_ORIGIN_ALLOW_ALL = True
ALLOWED_HOSTS = [
    "127.0.0.1", 
]

CORS_ALLOWED_ORIGINS = [
    "http://127.0.0.1", 
]
CORS_ALLOW_CREDENTIALS = False

INSTALLED_APPS = [
    .....
    "corsheaders"
]


MIDDLEWARE = [
    ......
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]

关于python - 对 Django CORS 问题使用react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69611485/

相关文章:

javascript - React 中的 JQuery 移动组件

css - Django 无效过滤器 : 'truncatechars_html'

java - Pycrypto AES GCM加密和Java解密

python - 将一维 numpy.array 索引为矩阵

python - 如何根据一级最大值过滤 MultiIndex 数据帧?

python - 不同客户端的 Django 权限

python - 无法在 View 中设置 Django 表单的字段值

python - 必须使用 x 实例作为第一个参数调用未绑定(bind)方法 f() (改为使用 str 实例)

javascript - 为什么我的 Container 组件从其他 reducer 获取状态对象?

javascript - 在 React 中将组件定义为对象