尝试使用Django和React在Web应用程序中发布axios请求并将其放入Web应用程序时出现403禁止错误

问题描述

我正在使用Django后端和React前端的Web应用程序。目前,我可以通过超级用户帐户创建文章,并将其列在前端。我现在正在尝试创建和更新,但始终出现以下错误

xhr.js:184 POST http://127.0.0.1:8000/api/ 403 (Forbidden)
Error: Request Failed with status code 403
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:69)

在我的研究中,我认为错误消息与csrftoken有关。我尝试在axios.post请求中添加以下语句:

xsrfCookieName: 'XSRF-TOKEN',xsrfheaderName: 'X-XSRF-TOKEN'

并且我尝试在我的settings.py文件添加以下语句:

CORS_ORIGIN_ALLOW_ALL = True

MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',...
]

INSTALLED_APPS = [
    ...
    'corsheaders',...
]

但是我仍然获得零成功。任何帮助将非常感激!谢谢你。

import { Form,Input,Button } from 'antd';

import axios from 'axios';

axios.defaults.xsrfheaderName = "X-CSrftoken"
axios.defaults.xsrfCookieName = 'csrftoken'

window.axios = require('axios');

/* window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest','X-CSRF-TOKEN': document.querySelector('Meta[name="csrf-token"]').getAttribute('title')
}; */

class CustomForm extends React.Component {

    onFinish = (values,requestType,articleID) => {
        console.log("Success:",values);
        const title = (values.title);
        const content = (values.content);

        console.log(this.props.requestType);

        const headers = { "X-CSrftOKEN": "<csrf_token_very_long_string_goes_here>" }
        //axios.post("/url/here/",{<form_data_to_post>},{ headers: headers })

        switch (this.props.requestType) {
            case 'post':
                return axios.post('http://127.0.0.1:8000/api/',{
                    title: title,content: content,headers: headers,xsrfCookieName: 'XSRF-TOKEN',xsrfheaderName: 'X-XSRF-TOKEN'
                })
                    .then(res => console.log(res))
                    .catch(err => { console.log(err); })

            case 'put':
                return axios.put(`http://127.0.0.1:8000/api/${articleID}/`,xsrfheaderName: 'X-XSRF-TOKEN'
                })
                    .then(res => console.log(res))
                    .catch(err => { console.log(err); })
        }
    };

    onFinishFailed = (errorInfo) => {
        console.log("Failed:",errorInfo);
    };

    render() {
        return (
            <div>
                <Form
                    name="basic"
                    initialValues={{
                        remember: true
                    }}
                    onFinish={this.onFinish}
                    onFinishFailed={this.onFinishFailed}
                >
                    <Form.Item label="Title" id='title' name="title">
                        <Input name="title" placeholder="Enter a Title" />
                    </Form.Item>
                    <Form.Item label="Content" id='content' name="content">
                        <Input name="content" placeholder="Enter the content of the announcement here" />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">{this.props.btnText}</Button>
                    </Form.Item>
                </Form>
            </div>
        );
    }
};

export default CustomForm;

解决方法

尝试一下对我有用

npm i js-cookie
import Cookies from 'js-cookie'

const csrftoken = Cookies.get('csrftoken') // Cookies from Django Domain

    const loginRequest = async () => {
        await Axios({
            method: "post",url: `/api/api-auth/login/`,headers: { 'X-CSRFToken': csrftoken },data: {}
        }).then((res) => {
            console.log(res.data);
        })
    }