Django Rest Framework + React I can’t return the Cookie

Asked

Viewed 30 times

0

I’m starting with Django and React development.

I tried to make a User Authentication page. When loading the User Registration page I call the API in Django to return the CSRF via Cookie and then I add to the header and form, but when loading the page, even calling the API, the Cookie is empty, with no value. But if I do test via Postman, I have the Cookie returned and with the CSRF updated, but via browser the Cookie is always blank.

This is my View on Django (The API):

@method_decorator(ensure_csrf_cookie, name='dispatch')
class GetCSRFToken(APIView):
    permission_classes = (permissions.AllowAny,)

        def get(self, request, format=None):
            return Response({'success': 'CSRF cookie definido'})

In React I have the component that makes your call to update the CSRF to send the form.

const CSRFToken = () => {
    const [csrftoken, setcsrftoken] = useState('')
    const getCookie = (name) => {
        let cookieValue = null
        if (document.cookie && document.cookie !== '') {
            let cookies = document.cookie.split(';')
            for (let i = 0; i < cookies.length; i++) {
                let cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1))
                    break
                }
            }
        }
        return cookieValue
    }

    useEffect(() => {
        const fetchData = async () => {
            try {
                axios.get(API_URL_GETCSRFCOOKIE)
                    .then(resp => {
                        setcsrftoken(getCookie('csrftoken'))
                    })
                    .catch(e => {
                        e.response.data.errors.forEach(
                            error => toastr.error('Erro', error)
                        )
                    })
            } catch (err) {
            }
        }
        fetchData()
        setcsrftoken(getCookie('csrftoken'))
    }, [])

    return (
        <input type='hidden' name='csrfmiddlewaretoken' value={csrftoken} />
    )
}

I looked into it, tried to debug it, but couldn’t identify where I was going wrong. Thank you for your attention to my problem.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.