首页 > 解决方案 > ReactJS 和 Django axios.post(403 错误代码)

问题描述

即使在对此类问题进行了一些回复后,我仍然收到错误代码 403(禁止(未设置 CSRF cookie。):/api/)。

这是我的代码:

JS

import axios from 'axios';

axios.defaults.xsrfHeaderName = 'X-CSRFTOKEN';
axios.defaults.xsrfCookieName = 'csrftoken';

class App extends Component {
    postHandler = (event) => {
        event.preventDefault();
        axios.get('http://localhost:8000/api/')
            .then((response) => {
                console.log(response)
            })
            .catch(error => alert(error));
    };
}

设置.py

CORS_ORIGIN_WHITELIST = 'http://localhost:3000',

视图.py

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello!")

其他任何东西都从 create-react-app 和 django-admin startproject 设置为默认值。

标签: djangoreactjsaxios

解决方案


这必须添加才能工作:

JS

axios.defaults.withCredentials = true;

设置.py

CORS_ALLOW_CREDENTIALS = True

视图.py

from django.http import HttpResponse
from django.views.decorators.csrf import ensure_csrf_cookie

# Create your views here.
@ensure_csrf_cookie
def index(request):
    return HttpResponse("Hello!")

推荐阅读