[英]Django dont set CSRF token on AJAX GET from angularJS
I am writing application with AngularJS on frontend and Django as REST service on backend. 我在前端使用AngularJS编写应用程序,而在后端使用Django作为REST服务编写应用程序。 I'm trying to send some JSON data using POST request, but facing with csrf-token issue (CSRF token missing or incorrect).
我正在尝试使用POST请求发送一些JSON数据,但是面临csrf令牌问题(CSRF令牌丢失或不正确)。 As far as i know, previously i should make a GET request on Django to obtain this token.
据我所知,以前我应该在Django上执行GET请求以获取此令牌。 So i have wrote simple view:
所以我写了一个简单的观点:
def get_csrf_token(request):
return HttpResponse(json.dumps({'success': True}))
I have added httpProvider defaults, and on start of angular application making GET request on view: 我添加了httpProvider默认值,并在启动角度应用程序时在视图上发出GET请求:
angular.module('app')
.config(function($httpProvider){
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
})
.run(function($http){
$http.get("http://127.0.0.1:8888/get_csrf_token/")
})
but this view dont set a CSRF token, and i still cannot do POST request. 但是此视图未设置CSRF令牌,并且我仍然无法执行POST请求。
If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token cookie. 如果您的视图未呈现包含csrf_token模板标记的模板,则Django可能未设置CSRF令牌cookie。 This is common in cases where forms are dynamically added to the page.
在将表单动态添加到页面的情况下,这很常见。 To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie() .
为了解决这种情况,Django提供了一个视图装饰器来强制设置cookie: sure_csrf_cookie() 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.