首页 > 解决方案 > 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?

标签: djangonginxsingle-page-applicationdjango-csrf

解决方案


CSRF 令牌总是随着每次页面加载而更新。它必须由 django 提供服务,因为 django 是提供和验证它的应用程序。将 index.html 文件放在您的 django 模板文件夹中,将其与您的索引视图一起提供,将 CSRF 令牌转换为 javascript 代码并在您的 ReactJS 代码中使用它

索引.html

...
<body>
<script>
     var csrftoken = '{{ csrf_token }}';
</script>
...
</body>
...

推荐阅读