[英]How to get and include the CSRF token in the header when working with REST API
我正在使用python Django创建REST API。客户端是在react中开发的,并且是独立的应用程序。我使用axios来触发http请求。我需要在每个post请求中传递CSRF令牌,但不是能够从浏览器获取CSRF令牌。
How to pass your CSRF when doing Ajax request? 进行Ajax请求时如何通过CSRF?
First, make sure you have the django.middleware.csrf.CsrfViewMiddleware in your middlewares list in your settings file. 首先,确保设置文件中的中间件列表中有django.middleware.csrf.CsrfViewMiddleware。 This middleware sets the CSRF_TOKEN in the cookie so you can retrieve it for your ajax request.
该中间件在cookie中设置CSRF_TOKEN,以便您可以针对ajax请求检索它。
Second, Django can now store the CSRF in the session. 其次,Django现在可以在会话中存储CSRF。 However, in your particular case you don't want the CSRF_TOKEN in the session.
但是,在特定情况下,您不需要会话中的CSRF_TOKEN。 Make sure you have CSRF_USE_SESSIONS = False (which is the default) to have the CSRF in the cookie.
确保您具有CSRF_USE_SESSIONS = False(这是默认值),以将CSRF包含在cookie中。
If you check the cookies you should now have a CSRF_TOKEN in there. 如果您检查Cookie,现在应该在那里有一个CSRF_TOKEN。 You can add it dynamically to your ajax request IF you are using jquery with the following code.
如果您使用带有以下代码的jquery,则可以将其动态添加到您的ajax请求中。
https://docs.djangoproject.com/en/1.11/ref/csrf/#setting-the-token-on-the-ajax-request https://docs.djangoproject.com/zh-CN/1.11/ref/csrf/#setting-the-token-on-the-ajax-request
I'm saying IF you use Jquery because you are using React, which doesn't need Jquery to do Ajax request, it's up to you how you do them. 我说的是,如果您使用Jquery是因为您使用的是React,则不需要Jquery来执行Ajax请求,这取决于您如何执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.