![](/img/trans.png)
[英]Django Rest Framework says CSRF verification failed despite CSRF token is included in axios POST header
[英]CSRF verification failed for Django despite Firebug saying there is a csrftoken underneath cookies tab. Why?
我遵循了在StackOverflow上推薦的很多內容,但無濟於事。 我也嘗試在html的各個地方擠壓{%csrf_token%},但似乎沒有一個起作用。 有什么建議么? 這是我的Django模板輸入按鈕:
<input id=saveWaypoints type=button value=Save disabled=disabled>
然后觸發此Javascript:
$('#saveWaypoints').click(function () {
var waypointStrings = [];
for (id in waypointByID) {
waypoint = waypointByID[id];
waypointStrings.push(id + ' ' + waypoint.lng + ' ' + waypoint.lat);
};
waypointStrings["csrfmiddlewaretoken"] = $('input[name=csrfmiddlewaretoken]').val();
$.post("{% url 'waypoints-save' %}", {
waypointsPayload: waypointStrings.join('\n')
}, function (data) {
if (data.isOk) {
$('#saveWaypoints').attr('disabled', 'disabled');
} else {
alert(data.message);
}
});
});
然后在views.py中調用此視圖:
def save(request):
'Save waypoints'
for waypointString in request.POST.get('waypointsPayload', '').splitlines():
waypointID, waypointX, waypointY = waypointString.split()
waypoint = Waypoint.objects.get(id=int(waypointID))
waypoint.geometry.set_x(float(waypointX))
waypoint.geometry.set_y(float(waypointY))
waypoint.save()
return HttpResponse(simplejson.dumps(dict(isOk=1)), content_type='application/json')
根據django docs的說明,您可以將令牌放置為請求的標頭,也可以將其 添加為有效負載 https://docs.djangoproject.com/en/1.8/ref/csrf/#ajax
您已經快到了,但是您只需將其作為自己的參數發送,而不是waypointsPayload
一部分:
$.post("{% url 'waypoints-save' %}", {
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
waypointsPayload: waypointStrings.join('\n')
}, function (data) {
...
});
Cookie是從中讀取令牌的替代位置,而不是從中讀取令牌(以防您不想在模板上添加令牌標簽)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.