简体   繁体   English

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

[英]403 Forbidden Error when trying to post and put a axios request in a web app using Django and React

I am working on a web application with a backend in Django and a frontend in React.我正在开发具有 Django 后端和 React 前端的 Web 应用程序。 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.在我的研究中,我相信错误消息涉及 csrftoken。 I have tried adding the following statements in my axios.post request:我尝试在 axios.post 请求中添加以下语句:

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

And I have tried adding the following statements in my settings.py file:我已经尝试在我的 settings.py 文件中添加以下语句:

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;

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);
        })
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试发出 POST 请求时出现禁止(CSRF 令牌丢失。)错误。 使用 React (Axios) 和 Django - Forbidden (CSRF token missing.) error when trying to make a POST request. Using React (Axios) and Django 登录 Django 时 Axios PUT 请求 403 被禁止 - Axios PUT Request 403 Forbidden when logged into Django 使用 React(Django 后端)进行 axios 调用时出现 403 禁止请求 - 403 Forbidden request when making an axios call with React (Django backend) 在React app中使用axios.post到Django端点时出现403错误代码 - 403 error code when using axios.post to Django endpoint in React app 在 Django 框架中发出 ajax Post 请求时出现 403 Forbidden 错误 - 403 Forbidden error when making an ajax Post request in Django framework django rest + axios放置请求错误403 - django rest + axios put request error 403 使用Docker在Django中使用POST数据发出urllib请求时,如何解决Forbidden 403错误? - How to resolve Forbidden 403 error when making a urllib request with POST data in Django using Docker? Django CSRF 和 axios 发布 403 Forbidden - Django CSRF and axios post 403 Forbidden Django Rest Framwork中的“ PUT”请求Ajax中禁止403错误 - forbidden 403 error in 'PUT' request Ajax in django rest framwork 无法在Django REST + React框架中执行axios PUT请求-错误403 - Cannot do axios PUT request in Django REST+React framework - Error 403
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM