django - 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 设置为默认值。
解决方案
这必须添加才能工作:
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!")
推荐阅读
- typescript - 递归类型别名属性访问
- phpmyadmin - PHPMyAdmin 输入区域变长了
- flutter - Flutter:调试控制台:字母:I,W是什么意思?
- gateway - APIGEE Spike Arrest 前端集成的最佳实践/实用用法
- .net-core - 为什么使用 Microsoft.Xml.SgmlReader 1.8.18 nuget 构建会输出此警告 MSB2346
- kotlin - 怎么预防!!通过ktlint?
- c# - “|=”运算符缓存静态字段值?
- javascript - 是否可以在函数内调用本地存储并在 Windows.onload 中使用它?
- tfs - TFS 签入:变更集评论策略中的内部错误。加载变更集评论策略策略时出错
- html - 当两个图像相互重叠时,如何允许一个图像溢出容器并隐藏另一个图像?