django - Acquiring CSRF token from Django when index.html is served by nginix
问题描述
I have a React SPA with a Django backend. Like most SPAs, there is an index.html file that needs to be served. But the problem is that this file is served with nginx, so user does not obtain csrf token required to make api calls. I don't really want to serve index.html, as it would require separating the file from the rest of npm run build
output and break the "just put it in /static/ directory" workflow, and also for caching reasons. Is there any other workaround?
解决方案
CSRF 令牌总是随着每次页面加载而更新。它必须由 django 提供服务,因为 django 是提供和验证它的应用程序。将 index.html 文件放在您的 django 模板文件夹中,将其与您的索引视图一起提供,将 CSRF 令牌转换为 javascript 代码并在您的 ReactJS 代码中使用它
索引.html
...
<body>
<script>
var csrftoken = '{{ csrf_token }}';
</script>
...
</body>
...
推荐阅读
- java - 出于某种原因,getArrayList 被视为 int
- ruby-on-rails - ActiveRecord,嵌套包括计数器
- pine-script - Pinescript:结合两个指标
- git - 有没有办法批量删除 GitHub 分叉存储库?
- mpi - 使用不同的用户名在 LAN 集群上运行 MPI
- android - MotionLayout 中的 Android CustomAttribute 以更改 TextView 中的文本
- visual-studio-2017 - 错误 CS1061“DeviceClient”不包含“SetInputMessageHandlerAsync”的定义
- git - Windows 10 上的 git bash 在尝试推送或拉取 GitHub 时报告“致命:遇到 AggregateException。发生了一个或多个错误”
- javascript - 在 Dygraph 的 Y 轴标签中添加逗号分隔符
- swift - 可选类型“AVCaptureDevice?”的值 必须解包为“AVCaptureDevice”类型的值