简体   繁体   中英

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. I'm trying to send some JSON data using POST request, but facing with csrf-token issue (CSRF token missing or incorrect). As far as i know, previously i should make a GET request on Django to obtain this token. 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:

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.

If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token 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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM