首页 > 解决方案 > Django CORS 请求外部重定向不允许

问题描述

我在从 react 向 django 视图发送 GET 请求时遇到问题,这些视图重定向到 GOOGLE_AUTH_ENDPOINT。,并且这个 url 命中了一个回调函数。但是在反应请求之后,它给出了这个错误:访问从源'localhost:3000'的“google auth url”(重定向自'localhost:8000')已被CORS策略阻止:对预检请求的响应没有通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

看法

class Glogin(APIView):
    params = {
        'client_id': CLIENT_ID,
        'response_type': 'code',
        'scope': 'openid email profile',
        'redirect_uri': CALLBACK_DOMAIN,
        'state': state,
    }
    
    if APPS_DOMAIN:
        params['hd'] = APPS_DOMAIN
    
    def get(self,request):
        request.session['googleauth_csrf'] = state
        request.session['next'] = request.META.get('HTTP_REFERER', None)
        print('Here')
        print(urlencode(self.params))
        return HttpResponseRedirect("%s?%s" % (GOOGLE_AUTH_ENDPOINT, urlencode(self.params)))
        #data = {'link':GOOGLE_AUTH_ENDPOINT, 'params':self.params}
        #return Response(data)

反应式

  static GLogIn() {
    return fetch("http://127.0.0.1:8000/glogin/", {
      //method: "POST",
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
      //body: JSON.stringify(body),
    }).then((response) => response.json());
  }

网址

urlpatterns = [
    path('', include(router.urls)),
    path('auth/', obtain_auth_token),
    path('login/',views.LogInViewSet.as_view()),
    path('logout/',views.LogOutViewSet.as_view()),
    path('articles/',views.ArticlesView.as_view()),
    path('articles/<int:pk>/',views.ArticlesView.as_view()),
    path('glogin/',views.Glogin.as_view()),
    path('callback/',views.Callback.as_view(), name='googleauth_callback'),

    #path('articales/',views.ArticlesViewSet.as_view())
]

设置.py

CORS_ORIGIN_WHITELIST = (
    'localhost:3000',
    #'accounts.google.com',
    #'accounts.google.com/o/oauth2/v2'
    
)


CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]

标签: reactjsdjangodjango-rest-frameworkgoogle-oauthdjango-cors-headers

解决方案


在 /etc/hosts 文件中为 127.0.0.1 放置一个主机条目

127.0.0.1 myfakedomain.local

然后将其添加到 CORS_ORIGIN_WHITELIST

'myfakedomain.local:8000',

然后您可以访问 cors 重定向。Chrome 会阻止它们,除非它们位于特殊域中。特别是本地主机。

然后将您的浏览器发送到http://myfakedomain.local:8000


推荐阅读