0

I am working on a web application with a backend in Django and a frontend in React. Currently I am able to create articles through my superuser account and list them on the frontend. I am now trying to create and update but I keep getting the following error:

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)

In my research I believe that the error message deals with csrftoken. I have tried adding the following statements in my axios.post request:

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

And I have tried adding the following statements in my settings.py file:

CORS_ORIGIN_ALLOW_ALL = True

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

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

But I still have had zero success. Any help would be much appreciated! Thank you much in advance.

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}/`, {
                    title: title,
                    content: content,
                    headers: headers,
                    xsrfCookieName: 'XSRF-TOKEN',
                    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;
Chantal Thomas
  • 73
  • 1
  • 2
  • 4

1 Answers1

2

Try this It works for me

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);
        })
    }
Abir Islam
  • 21
  • 3