我正在使用Django和Angular JS來訪問Google Drive API。我正在關注Google的this文檔。 FLOW.step1_get_authorize_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
)。使用谷歌oauth2時的狀態碼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(https://docs.djangoproject.com/en/1.11/ref/settings/#allowed-hosts) - 當DEBUG爲True並且ALLOWED_HOSTS爲空時,主機根據['localhost','127.0 .0.1','[:: 1]']。我將DEBUG設置爲True。 –
對。我刪除了該評論。我不是故意要問這個。請參閱更新的一個。 –