简体   繁体   中英

Django - Sending POST request from javascript

I have a JS event-triggered function which goal is send a POST request in order to update some objects in my database. The event which triggers the function is a drop-event, so i initially avoided using forms to pass my request, but tell me if i did wrong.

Big Edit:

I found that my mistake was to not include the csrf_token on my post request. However, i still have an error: my post request comes in empty when i do print(request.POST) on my django view.

My JS file:

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

const dragDrop = function (e) {
    e.preventDefault()
    
    const droppedElId = e.dataTransfer.getData('Text/html').split('__id-')[1]
    const request = new XMLHttpRequest()
    request.open('POST', '', true)
    request.setRequestHeader('X-CSRFToken', csrftoken)
    request.setRequestHeader('Content-Type', 'application/json')
    // request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
    request.send(JSON.stringify({
        "request_name":"change-extra-fields",
        "type":"increase",
        "id":droppedElId,
    }))
}

The query-dict of the request.POST is empty when i do this. However, the request works if i change the Content-Type header to application/x-www-form-urlencoded , but it puts everything on the same key.

Example:

Result with 'application/json':

<QueryDict: {}>

Result with 'application/x-www-form-urlencoded':

<QueryDict: {'{"request_name":"change-extra-fields","type":"increase","id":"8"}': ['']}>

Anyways, i think that 'application/json' should be working and i have no idea why it isn't..

There is a typo I think

request.setRequestHeader('Content-Type', 'application/json');

As you mentioned in comments, your post request required you to be authenticated.

So, you first need to authenticate/login to the site(using another Ajax call perhaps). If the site supports jwt/api authentication you would get a token back which you have to send in attached with header in next (post)request. it would be something like this

xhr.setRequestHeader('Authorization', 'Bearer arandombereartoken');

if the site uses session/cookie authentication then I suggest consider using jQuery and its Ajax functions. I this this (2nd one) should be helpful.

UPDATE:

if you want to get data as application/json you have to look in the body of the request

if request.method == "POST":
        print(request.body)

this would give you a byte object. you have load it to a json if you want json. request.POST is only for Content-Type 'application/x-www-form-urlencoded'

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