reactjs - 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',
]
解决方案
在 /etc/hosts 文件中为 127.0.0.1 放置一个主机条目
127.0.0.1 myfakedomain.local
然后将其添加到 CORS_ORIGIN_WHITELIST
'myfakedomain.local:8000',
然后您可以访问 cors 重定向。Chrome 会阻止它们,除非它们位于特殊域中。特别是本地主机。
然后将您的浏览器发送到http://myfakedomain.local:8000
推荐阅读
- angular - Primeng 数据表将扩展器图标更改为按钮并在扩展事件上传递数据
- mapbox - 使用 MapboxGL JS 绘制空值或无数据值,使用 setPaintProperty 绘制圆形颜色并停止数组
- javascript - 使用 Chrome IE Tab 扩展从 chrome 上的菜单单击在 IE 中启动弹出窗口
- asp.net - 用于接受英语和波斯语文本的正则表达式
- c# - xamarin iOS 应用程序中的 WebException SSL 错误,服务托管在 azure 上,仅适用于英国的 EE 移动网络
- android - Android Q,以编程方式连接到不同的 WiFi AP 上网
- javascript - 如何将搜索子域的 PCRE 正则表达式重写为 Javascript 正则表达式?
- ruby-on-rails - 如何使用 Koala Gem For Ruby On Rails 获取喜欢我们页面的 Facebook 用户列表
- mql4 - 如何区分旧的 Close[1] 和新的 Close[1]?
- .net - 更新 JWT Token .net Core Web API 以添加新的声明