'Get request sometimes returns "There was an error: Unexpected token e in JSON at position 0"

Sometimes it will work, it seems to work when I open a new browser window. However, I can't recreate a consistent scenario when it works

This is the request i'm trying to make

 login(): void {
    // const loginFormValues = JSON.stringify(this.loginForm.getRawValue())
    this.userService.login(this.loginForm.getRawValue()).subscribe({
      next: (data) => {
        console.log(data);
        this.router.navigate(['/']);
      },
      error: (error) => {
        this.router.navigate(['/login']);
        console.log('There was an error: ' + error.message);
      },
    });
  }

this.loginForm.getRawValue() gives me the following object

{username: 'jocelyn', password: '123456'}

This is what the backend does


class LoginView(APIView):
    def post(self, request):
        username = request.data['username']
        password = request.data['password']

        # We find the first user since username is unique
        user = User.objects.filter(username=username).first()

        if user is None:
            raise AuthenticationFailed('User not found!')

        if not user.check_password(password):
            raise AuthenticationFailed('Incorrect password!')

        # Token expires in sixty minutes
        payload = {
            'id': user.id,
            'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
            # Date when token is created
            'iat': datetime.datetime.utcnow()
        }

        token = jwt.encode(payload, 'secret', algorithm='HS256')

        response = Response()
        response.set_cookie(key='jwt', value=token, httponly=True)
        response.data = {'jwt': token}
        
        return response



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source