【发布时间】:2018-02-25 11:35:33
【问题描述】:
我正在使用带有 Angular JS 的 Django 来访问 Google Drive API。我正在关注来自 Google 的 this 文档。 FLOW.step1_get_authorize_url() 给了我类似于页面上提到的示例 URL 的 URL。但是问题是return HttpResponseRedirect(authorize_url)之后浏览器并没有重定向到authorize_url,报错如下图(Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8000' is therefore not allowed access. The response had HTTP status code 405)。
但如果我复制粘贴 URL,它就可以正常工作。
oauth2 函数如下所示。
def index(request):
FLOW = flow_from_clientsecrets(
settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON,
scope='https://www.googleapis.com/auth/drive',
redirect_uri='http://127.0.0.1:8000/oauth2callback/'
)
FLOW.params['access_type'] = 'offline'
authorize_url = FLOW.step1_get_authorize_url()
return HttpResponseRedirect(authorize_url)
这里是 oauth2callback 函数。
def auth_return(request):
credential = FLOW.step2_exchange(request.GET)
return HttpResponseRedirect("/mycustomurl")
我使用this 在 Django 服务器端启用 CORS。这是我在 Angular 中调用 oauth2 的服务部分。
(function () {
'use strict';
angular.module('myApp')
.service('myService', function ($http) {
this.saveToDrive = function (startYear, endYear, shape) {
var config = {
params: {
start: '1999',
end: '2002',
action: 'download-to-drive'
},
headers: {
'Access-Control-Allow-Origin': '*',
'X-Requested-With': null
}
}
var promise = $http.get('/oauth2/', config)
.then(function (response) {
return response.data;
});
return promise;
};
});
})();
请建议我在这里缺少什么。非常感谢任何帮助或建议。
【问题讨论】:
-
您在
settings中添加了CORS_ORIGIN_ALLOW_ALL=True或CORS_ORIGIN_WHITELIST=('127.0.0.1:8000', )吗? -
根据 doc (docs.djangoproject.com/en/1.11/ref/settings/#allowed-hosts) - 当 DEBUG 为 True 且 ALLOWED_HOSTS 为空时,将根据 ['localhost', '127.0.0.1', '[::1]'] 验证主机.我已将 DEBUG 设置为 True。
-
对。我删除了那条评论。我不是故意问这个的。请查看更新的。
-
是的,我的设置中有
CORS_ORIGIN_WHITELIST = ('127.0.0.1:8000',) -
您是否在 Google API 控制台的
Authorized Javascript Origins中添加了“127.0.0.1:8000”作为 OAuth2 的 Web 应用程序凭据?
标签: angularjs django google-oauth http-status-code-405