【发布时间】:2013-12-20 10:25:18
【问题描述】:
我已成功设置TokenAuthentication 并生成了用户在身份验证后成功接收的令牌。不幸的是,我无法毫无错误地将令牌发送到 API (DRF TokenAuthentication)。该令牌是硬编码的,用于测试和我使用 djangos runserver 运行。我从回复中看到只允许POST 和OPTIONS,但我可以curl 没有任何问题:
curl -X GET http://127.0.0.1:8000/api-token-auth -H 'Authorization: Token a83ff8dabb7fc7b800d381fd3994dfe2051cc0c2'
实施
控制器/Login.js:
reSignInCommand: function (aToken) {
var me = this;
Ext.Ajax.request({
url: 'http://127.0.0.1:8000/api-token-auth/',
method: 'GET',
disableCaching: false,
timeout: 10000,
useDefaultXhrHeader: false,
headers: {
'Authorization' : 'Token a83ff8dabb7fc7b800d381fd3994dfe2051cc0c2'
},
success: function(response) {
console.log("success");
},
failure: function(response) {
console.log("failure");
}
});
api/urls.py:
from django.conf.urls import patterns, url, include
urlpatterns += patterns('',
url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token'),
)
调试:
Request URL:http://127.0.0.1:8000/api-token-auth/
Request Method:GET
Status Code:405 METHOD NOT ALLOWED
Request headers:
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:da,zh;q=0.8,de;q=0.6,en;q=0.4
Authorization:Token a83ff8dabb7fc7b800d381fd3994dfe2051cc0c2
Cache-Control:no-cache
Connection:keep-alive
Host:127.0.0.1:8000
Origin:http://127.0.0.1
Pragma:no-cache
Referer:http://127.0.0.1/sencha/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
Response headers:
HTTP/1.0 405 METHOD NOT ALLOWED
Date: Fri, 20 Dec 2013 10:19:50 GMT
Server: WSGIServer/0.1 Python/2.7.5
Vary: Accept, Cookie
Access-Control-Allow-Origin: *
Content-Type: application/json
X-Frame-Options: SAMEORIGIN
Allow: POST, OPTIONS
【问题讨论】:
-
你能
curl到http://127.0.0.1:8000/api-token-auth/吗(见尾部斜线)? -
这意味着你只能卷曲到
http://127.0.0.1:8000/api-token-auth,而不是http://127.0.0.1:8000/api-token-auth/。如果缺少/,Django 通过重定向添加尾随。 -
如果我删除最后一个反斜杠,我会得到
XMLHttpRequest cannot load http://127.0.0.1:8000/api-token-auth. The request was redirected to 'http://127.0.0.1:8000/api-token-auth/', which is disallowed for cross-origin requests that require preflight.,值得一提的是我已经启用了CORS:CORS_ORIGIN_ALLOW_ALL = Trueinsettings.py -
将缺少的斜杠添加到
curlURL 并显示结果。 -
curl http://127.0.0.1:8000/api-token-auth/=>{"detail": "Method 'GET' not allowed."}%
标签: django sencha-touch django-rest-framework