Аутентифицированный запрос на выборку работает только половину времени - PullRequest
1 голос
/ 19 мая 2019

Я пытаюсь сделать аутентифицированный запрос на выборку из компонента реагирования на мою серверную часть django api, однако он работает только половину времени (обычно сразу после входа в систему и аутентификации пользователя). В остальную половину времени я получаю 401 (неавторизованный): «Неавторизованный: / API / платежи / сбор /»

Мои инструменты redux dev ясно показывают, что токен присутствует: токен присутствует

Может кто-нибудь помочь мне определить, почему это так?

FRONTEND: Метод отправки моего реагирующего компонента:

async submit(ev) {
    // User clicked submit

    let {stripeToken} = await this.props.stripe.createToken({name: this.state.cardholderName})
    let amount = this.state.amount

    this.setState({
      isLoading: true,
    })
    let response = await fetch("http://127.0.0.1:8000/api/payments/charge/", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: 'JWT ' + this.props.token

        },
        body: JSON.stringify({stripeToken, amount})
    })

    if (response.ok) console.log("Purchase Complete!")
    if (response.ok) this.setState({complete: true, isLoading: false});

  }
const mapStateToProps = state => {
  return {
    token: state.token
  }
}

export default injectStripe(connect(mapStateToProps)(withStyles(styles)(CheckoutForm)))

BACKEND: апи / views.py

class ChargeAndCreateCustomerAPIView(APIView):

    permission_classes = [permissions.IsAuthenticated]
    parser_classes = (JSONParser, )

    def post(self, request, *args, **kwargs):

        # Check if user is authenticated
        if self.request.user.is_authenticated:

            print('USER IS AUTHENTICATED')

            user = self.request.user

            if user.profile.stripe_customer_id != '':
                print('CUSTOMER ID IS: ' + str(user.profile.stripe_customer_id))
            else:
                print('CUSTOMER HAS NO ID')
                customer = stripe.Customer.create(
                    source=request.data['token']['id'],
                    email='paying.user@example.com',
                )
                user.profile.stripe_customer_id = customer.id
                user.save()

                print('created new customer id: ')
                print(user.profile.stripe_customer_id)

            amount = int(request.data['amount'])*100
            charge = stripe.Charge.create(
                amount=amount,
                currency='usd',
                description='A Django charge',
                customer=user.profile.stripe_customer_id
            )

        return Response(status=200)

settings.py

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
        # 'rest_framework.authentication.BasicAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES' : (
        #'rest_framework.permissions.IsAuthenticated',
        #'rest_framework.permissions.IsAuthenticatedOrReadOnly',
        'rest_framework.permissions.AllowAny',
    )
}

КОГДА ЭТО НЕ СДЕЛАНО: ошибка консоли: ошибка консоли

Ошибка сервера django в терминале: Ошибка терминала Django

...