【发布时间】:2017-09-11 14:19:44
【问题描述】:
我已经开始阅读“轻量级 Django”https://github.com/lightweightdjango 以了解有关 Django 和客户端 JavaScript 的更多信息。在测试使用Backbone.js 创建的LoginView 时,我收到Forbidden(403) CSRF verification failed.Request aborted. 消息,正如这篇文章中指出的那样:CSRF verification failing in django/backbone.js。
首先,我想在表单中插入{% csrf_token %} 模板标签,但是当我这样做时,服务器会给我一个POST / HTTP/1.1" 405 0 - Method Not Allowed (POST) : / 消息。
由于 AJAX X-CSRFToken 请求标头是使用 $.ajaxPrefilter() 设置的,我无法弄清楚问题所在。
当我使用 httpie 使用超级用户详细信息执行 POST 请求时,一切正常,如下例所示:
HTTP/1.0 200 OK
Allow: POST, OPTIONS
Content-Type: application/json
Date: Mon, 11 Sep 2017 13:49:49 GMT
Server: WSGIServer/0.2 CPython/3.6.2
Vary: Cookie
X-Frame-Options: SAMEORIGIN
{
"token" : some_value
}
通过“检查元素”功能使用控制台,我收到以下消息:
Response headers:
Allow: GET, HEAD, OPTIONS
Content-Length: 0
Content-Type: text/html; charset=utf-8
Date: Mon, 11 Sep 2017 14:03:06 GMT
Server: WSGIServer/0.2 CPython/3.6.2
X-Frame-Options: SAMEORIGIN
Request headers:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Content-Length: 116
Content-Type: application/x-www-form-urlencoded
Cookie: csrftoken=some_value
Host: 127.0.0.1:8000
Referer: http://127.0.0.1:8000/
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:55.0) Gecko/20100101 Firefox/55.0
我不知道是TemplateView 是罪魁祸首还是我遗漏了什么:
urls.py:
from django.conf.urls import url,include
from django.views.generic import TemplateView
#from django.views.decorators.csrf import ensure_csrf_cookie
from rest_framework.authtoken.views import obtain_auth_token
from board.urls import router
urlpatterns = [
url(r'^api-auth/', obtain_auth_token, name='api-login'),
url(r'^api-root/', include(router.urls)),
url(r'^$', TemplateView.as_view(template_name='board/index.html')),
]
有人能解释一下到底发生了什么吗? 谢谢!
【问题讨论】:
标签: javascript python django backbone.js