API 从 Angular 应用到 Django REST 的请求 API - 被 CORS 阻止
API request from Angular App to Django REST API - blocked by CORS
我有一个正在运行的 Angular 应用程序,它从 Django REST api 获取数据。当我向某些端点发出请求但由于在其他端点上为 blocked by CORS
而失败时,api 请求成功。
我在 Django 应用程序中的 CORS 配置:
白名单:
CORS_ORIGIN_WHITELIST = (
'http://localhost:4200', # my angular app
'http://localhost:8080',
)
中间件:
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
]
已安装的应用程序:
INSTALLED_APPS = [
...
'corsheaders',
]
当我在我的 angular 应用程序中发出这个获取请求时,它成功了,我得到了我期望的结果
Angular 请求:
public getProviders(searchParams: ProviderSearchParams): Observable<ProviderSearchResult> {
const p = this.serializeParams(searchParams, new HttpParams());
return this.http.get<any>(`${this.base_url}/providers/`, {params: p})
.pipe(map(this.deserializeAs(ProviderSearchResult)));
}
Django 端点
# urls
path('', views.ProviderList.as_view(), name="api_provider_list"),
# views
class ProviderList(generics.ListAPIView):
"""
View all providers.
"""
queryset = Provider.objects.filter(is_accepted=True)
filter_backends = [DjangoFilterBackend,
filters.SearchFilter, filters.OrderingFilter]
filterset_fields = ['name', 'branches__city', 'branches__area']
search_fields = ['name', 'branches__name',
'branches__city', 'branches__area']
ordering_fields = ['name', 'created_date']
pagination_class = PageNumberPagination
def get_serializer_class(self):
if self.request.user.is_staff:
return AdminProviderSerializer
return PublicProviderSerializer
但是,当我向 generics.RetrieveUpdateDestroyAPIView
发出请求时,它似乎失败并出现错误 blocked by CORS
。这是一个例子:
Angular 请求:
public getProviderBySlug = (slug: string): Observable<Provider> =>
this.http.get<any>(`${this.base_url}/providers/${slug}`)
.pipe(map(this.deserializeAs(Provider)))
Django 端点
# urls
path('<slug:slug>/', views.ProviderDetail.as_view(), name="api_provider_details"),
# views
class ProviderDetail(generics.RetrieveAPIView):
"""
Returns a single provider
"""
queryset = Provider.objects.all()
serializer_class = PublicProviderSerializer
def get_object(self):
return Provider.objects.get(slug=self.kwargs.get('slug', None))
似乎对 generics.RetrieveUpdateDestroyAPIView
和 generics.RetrieveAPIView
的请求导致了这个 CORS 错误
错误
Access to XMLHttpRequest at 'http://localhost:8000/api/providers/icc' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
请加/
像那样
this.http.get<any>(`${this.base_url}/providers/${slug}/`) <---- '/' is there
我有一个正在运行的 Angular 应用程序,它从 Django REST api 获取数据。当我向某些端点发出请求但由于在其他端点上为 blocked by CORS
而失败时,api 请求成功。
我在 Django 应用程序中的 CORS 配置:
白名单:
CORS_ORIGIN_WHITELIST = (
'http://localhost:4200', # my angular app
'http://localhost:8080',
)
中间件:
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
]
已安装的应用程序:
INSTALLED_APPS = [
...
'corsheaders',
]
当我在我的 angular 应用程序中发出这个获取请求时,它成功了,我得到了我期望的结果
Angular 请求:
public getProviders(searchParams: ProviderSearchParams): Observable<ProviderSearchResult> {
const p = this.serializeParams(searchParams, new HttpParams());
return this.http.get<any>(`${this.base_url}/providers/`, {params: p})
.pipe(map(this.deserializeAs(ProviderSearchResult)));
}
Django 端点
# urls
path('', views.ProviderList.as_view(), name="api_provider_list"),
# views
class ProviderList(generics.ListAPIView):
"""
View all providers.
"""
queryset = Provider.objects.filter(is_accepted=True)
filter_backends = [DjangoFilterBackend,
filters.SearchFilter, filters.OrderingFilter]
filterset_fields = ['name', 'branches__city', 'branches__area']
search_fields = ['name', 'branches__name',
'branches__city', 'branches__area']
ordering_fields = ['name', 'created_date']
pagination_class = PageNumberPagination
def get_serializer_class(self):
if self.request.user.is_staff:
return AdminProviderSerializer
return PublicProviderSerializer
但是,当我向 generics.RetrieveUpdateDestroyAPIView
发出请求时,它似乎失败并出现错误 blocked by CORS
。这是一个例子:
Angular 请求:
public getProviderBySlug = (slug: string): Observable<Provider> =>
this.http.get<any>(`${this.base_url}/providers/${slug}`)
.pipe(map(this.deserializeAs(Provider)))
Django 端点
# urls
path('<slug:slug>/', views.ProviderDetail.as_view(), name="api_provider_details"),
# views
class ProviderDetail(generics.RetrieveAPIView):
"""
Returns a single provider
"""
queryset = Provider.objects.all()
serializer_class = PublicProviderSerializer
def get_object(self):
return Provider.objects.get(slug=self.kwargs.get('slug', None))
似乎对 generics.RetrieveUpdateDestroyAPIView
和 generics.RetrieveAPIView
的请求导致了这个 CORS 错误
错误
Access to XMLHttpRequest at 'http://localhost:8000/api/providers/icc' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
请加/
像那样
this.http.get<any>(`${this.base_url}/providers/${slug}/`) <---- '/' is there