[英]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.