简体   繁体   中英

How to add CSRF token for Ajax Request not using jQuery

I want to send some data from the javascript file to the views file in my Django app using an Ajax request. However I am doing this using only Javascript as I am not familiar with jQuery and don't now how to add the CSRF token.

Here is my Javascript Code:

    const request = new XMLHttpRequest();
        request.open("POST", "/list");
    var csrftoken = Cookies.get('csrftoken');

    let data = {
        items: JSON.stringify(items)
    }
    request.setRequestHeader( 'X-CSRF-TOKEN', csrftoken);
    request.send(data);

I have tried using Cookies.get('csrftoken') and getCSRFTokenValue() but am unsure how to send the token once acquired.

In the Developers' Console it says: Failed to load resource: the server responded with a status of 403 (Forbidden)

If you don't have a form tag within it you have to added the csrf_token so you have to add a decorator just before your view

@csrf_exempt 
Def your_view(request):

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