Home > OS >  TypeError: Failed to execute 'fetch' on 'Window': Invalid name while fetching to
TypeError: Failed to execute 'fetch' on 'Window': Invalid name while fetching to

Time:07-23

trying to create a E-commerce website using django, django RestAPI & React! i'm using Rest framework simple jwt for authorization & created a view of ' MyTokenObtainPairView' to retreat token where the user data will be stored. everything is fine but i can't fetch the token from the front end after logging in & it shows me the error. what am i doing wrong & how to fix it??

#Settings: 

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
}


SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=90),
    'ROTATE_REFRESH_TOKENS': True,
    'BLACKLIST_AFTER_ROTATION': True,
    'UPDATE_LAST_LOGIN': False,

    'ALGORITHM': 'HS256',
    'VERIFYING_KEY': None,
    'AUDIENCE': None,
    'ISSUER': None,
    'JWK_URL': None,
    'LEEWAY': 0,

    'AUTH_HEADER_TYPES': ('Bearer',),
    'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',
    'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',

    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',
    'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser',

    'JTI_CLAIM': 'jti',

    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
    'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}

views:

from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)

        # Add custom claims
        token['username'] = user.username
        # ...

        return token

class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer

@api_view(['GET','POST'])
def getRoutes(request):
    routes = [
        '/api/token',
        '/api/refresh',
    ]
    return Response(routes)

Urls.py:

from . import views
from .views import *
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)

urlpatterns = [
    path('',views.getRoutes,name='get_routes'),
    path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]

react front-end :

const [username,setUsername] = useState('')
const [password,setPassword] = useState('')

const loginUser = async (e)=>{
        e.preventDefault()
        try {
          let response = await fetch('http://127.0.0.1:8000/api/token/',{
            method:'POST',
            headers:{
              'Content-Type:':'application/json',
            },
            body:JSON.stringify({'username':e.target.username.value,'password':e.target.password.value})
// tried to use useState variables to hold the value & send it through body of fetch!
          })
          const data = await response.json()
          setAuthTokens(data)

        }  catch (error) {
          console.log("failed:",error)
        }
      }

form:

<form className="form" onSubmit={loginUser}>
                <h5>Username:</h5>
                <input type="text" value={username} name='username' onChange={(e)=>setUsername(e.target.value)} />
                <h5>Password:</h5>
                <input type="password" value={password} name='password' onChange={(e)=>setPassword(e.target.value)} />
                <button className="login-btn" type='submit'>Sign-in</button>
            <p className="terms">By continuing, you agree to Amazon's Conditions of Use and Privacy Notice.</p>
            <div className="new-acc">
                <p className='new'>New to Amazon?</p>
                <hr />
                <br />
                <button className="create-btn">Create Your Amazon Account</button>
            </div>
            </form>

CodePudding user response:

In the headers for your fetch call, you included a colon in the Content-Type header key:

'Content-Type:':'application/json',

should be

'Content-Type':'application/json',

  • Related