2017-09-16 41 views
0

我正在使用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

enter image description here

但是,如果我复制粘贴的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; 
     }; 

    }); 

})(); 

请建议我在这里丢失什么。任何帮助或建议,高度赞赏。

+0

您在'settings'中添加了'CORS_ORIGIN_ALLOW_ALL = True'或'CORS_ORIGIN_WHITELIST =('127.0.0.1:8000',)'? –

+0

根据doc(https://docs.djangoproject.com/en/1.11/ref/settings/#allowed-hosts) - 当DEBUG为True并且ALLOWED_HOSTS为空时,主机根据['localhost','127.0 .0.1','[:: 1]']。我将DEBUG设置为True。 –

+0

对。我删除了该评论。我不是故意要问这个。请参阅更新的一个。 –

回答

0

我发现它是一个小设计问题,而不是代码问题。我将发送oauth2请求的逻辑与客户端分开,并且在oauth2请求之后,我通过params选项向内部API发送了请求。现在它工作正常。