我一直收到CORS错误
Request header field Accept-Encoding is not allowed by Access-Control-Allow-Headers
只有当我访问我的一个API的实时/生产服务器时才会发生这种情况。
可以在没有任何CORS错误的情况下访问所有其他API。
WORKING API(无CORS错误):
qset = (
Dummyproduct.objects
.order_by('-updated',)
.values('storelogo', 'storeimage', 'productname', 'productimage', 'productprice',)
)
return Response(qset)
BROKEN API(CORS错误):
qset = (
{'description': 'Total Products' , 'stats':Product.objects.count(), 'icon':'face', 'color':'red','percent':89, },
{'description': 'Total Swipes' , 'stats':Variation.objects.count(), 'icon':'person', 'color':'greed', 'percent':40,},
{'description': 'Total Returns' , 'stats':User.objects.count(), 'icon':'refresh', 'color':'red', 'percent':62,},
{'description': 'Total Purchases' , 'stats':User.objects.count(), 'icon':'money', 'color':'green', 'percent':32,}
)
return Response(qset)
服务器(Django):
类CorsMiddleware(对象):
def process_response(self, request, response):
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT'
# response['Content-Type'] = 'application/json'
response['Accept'] = 'application/json'
return response
App(AngularJS):
function ($httpProvider) {
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
$httpProvider.defaults.headers.get = {};
}
实际的API包含以下标题(Chrome>网络工具):
Accept:application/json
Access-Control-Allow-Methods:POST, GET, OPTIONS, PUT
Access-Control-Allow-Origin:*
Allow:GET, HEAD, OPTIONS
Content-Type:application/json;q=0.8
Date:Tue, 17 May 2016 04:02:04 GMT
Server:WSGIServer/0.1 Python/2.7.10
X-Frame-Options:SAMEORIGIN
答案 0 :(得分:0)
解决了这一点。非常简单 - 我很简单需要一个尾随斜线。奇怪的是在本地使用页面 - 我没有CORS错误。很方便。
/mypage
代替/mypage/
答案 1 :(得分:0)
您需要将Access-Control-Request-Headers
设置为值Accept-Encoding
才能解决此问题。检查this。