我正在使用最新版本的Django和Django Rest Framework . 我的Web应用程序提供了目前仅由前端使用的API .
我正在使用相同的API路由创建chrome扩展 .
当我使用本地服务器runserver命令时,我没有问题 . 当服务器在HTTPS后运行时,我一直有403错误 .
{"detail":"CSRF Failed: Referer checking failed - no Referer."}
我使用的视图如下:
@method_decorator(csrf_exempt, name='dispatch')
class ObtainAuthToken(APIView):
permission_classes = (AllowAny,) #maybe not needed in your case
def post(self, request):
username = request.POST['username'].lower()
password = request.POST['password']
user = authenticate(username=username, password=password)
payload = dict()
if user is not None:
token, created = Token.objects.get_or_create(user=user)
payload['token'] = token.key
payload ["success"] = True
else:
payload['error'] = "Credentials not valid or user inactive"
payload ["success"] = False
payload["operation"] = "Obtain Authentication Token"
payload ["timestamp"] = get_timestamp()
return Response(payload)
AJAX Call如下:
$.ajax({
url: endpoint + "api/1.0/get_auth_token/",
type: 'POST',
// Fetch the stored token from localStorage and set in the header
data: formData,
dataType: "json",
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData:false,
xhrFields: {
withCredentials: false
},
headers: {
'Cache-Control': 'no-cache'
},
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRFToken', csrf_val);
},
success: function(response){
console.log(response);
}
});
奇怪的是,当我使用Postman时,它完全适用于所有情况 . 我设置 Headers 是相同的,我仍然无法使它工作 .
谢谢你的帮助