ajax - 无法使用 DRF API 上的 AJAX 调用设置 cookie
问题描述
我有一个 Django Rest API,它在响应对象中设置 cookie。当我点击可浏览的 API 时,浏览器将 cookie 存储在 Application>Cookies 下。当我尝试使用 AJAX 调用重现相同的结果时,cookie 不会自动存储;虽然我确实在 AJAX 调用中得到了一个响应对象。
我的代码如下
视图.py
class UserLogin(generics.GenericAPIView):
serializer_class = serializers.UserLoginSerializer
permission_classes = (
permissions.AllowAny,
)
def finalize_response(self, request, *args, **kwargs):
"""
Set Authorization in cookie.
"""
response_obj = super(UserLogin, self).finalize_response(
request, *args, **kwargs)
if request.POST and response_obj.status_code == 200:
response_obj['Authorization'] = 'Token '\
+ response_obj.data['auth_token']
print 'COOKIE NOT SET'
response_obj.set_cookie(
'Authorization', response_obj['Authorization'])
print 'COOKIE SET'
return response_obj
def post(self, request):
"""
If serializer is valid.
- call action.
"""
serializer = self.get_serializer(
data=request.data)
if serializer.is_valid():
user = serializer.validated_data.get('user')
token, boolean = Token.objects.get_or_create(user=user)
if not boolean:
token.created = datetime.datetime.now()
token.save()
# user.login_attempts = 0
user.save()
data = serializers.TokenSerializer(token).data
return response.Response(
data=data,
status=status.HTTP_200_OK,)
return response.Response(
data=serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
序列化程序.py
class UserLoginSerializer(serializers.Serializer):
def __init__(self, *args, **kwargs):
super(UserLoginSerializer, self).__init__(*args, **kwargs)
self.user = None
self.fields[User.USERNAME_FIELD] = serializers.CharField()
password = serializers.CharField(
style={'input_type': 'password'})
def validate(self, data):
username = data.get(User.USERNAME_FIELD).lower()
password = data.get('password')
try:
user = User.objects.get(username=username)
except:
raise serializers.ValidationError(
messages.INVALID_CREDENTIALS_ERROR)
data['user'] = user
user_service = UserService()
is_valid = user_service.verify_account(user, password)
if not is_valid:
raise serializers.ValidationError(
messages.INACTIVE_ACCOUNT_ERROR)
return data
class Meta:
fields = (User.USERNAME_FIELD, 'password')
ajax 调用
$(document).ready(function() {
$('form').submit(function(event) {
var formData = {
'username' : $('input[name=username]').val(),
'password' : $('input[name=password]').val(),
};
// process the form
$.ajax({
type : 'POST',
url : 'http://13.232.122.165/users/login/',
data : formData,
dataType : 'json',
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
location.href = "localhost:5000/profile"
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
解决方案
cookie 已附加,但除非您在请求 url 域上,否则您无法从开发人员工具中看到它。尝试使用 ajax 登录并在浏览器上点击请求 url(任何端点),您将看到 cookie。
推荐阅读
- php - 单击php中迭代列表中的行后如何显示单个数据库行?
- geolocation - 根据地址获取确切的纬度,经度
- excel - 当不同工作簿工作表上的参考标准范围时,SUMIFS 返回零
- html - CSS 灵活的布局,用于以链式方式排列有序的块元素
- reactjs - React JS 如何在 Hook 中的页面之间传递数据(useEffect)
- c# - ASP.NET MVC RenderPartial 错误代码 CS0029
- reactjs - React onSubmit 不会提交 textarea 值
- c++ - 使用 C++20 概念来避免 std::function
- angular - 我不断收到“类型 void 上不存在属性订阅”的错误
- java - 60000 毫秒后元数据中不存在主题 Iamtopic