1
votes

I want to retrieve the user details for displaying the username of the user who is logged-in I need to fetch the username from "http://127.0.0.1:8000/rest-auth/user/" from django-rest-auth I am new to reactjs and tried the authentication which was successfully but couldn't get pass this.

I have tried this so far

axios.get(`http://127.0.0.1:8000/rest-auth/user/`,
            {
                headers: { 'Authorization': "token " + localStorage.getItem('token') }
            }
        ).then(res => {
            console.log(res)
        }).catch(Error => {
            console.log(Error)
        })

which returns the forbidden 403 error;

Errors

Error: Request failed with status code 403
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:61)

Also in the above code I also specified the headers in the following manner headers: { 'Authorization': "token key_from_DRF " } but no luck

I have also tried this

axios.get(`http://127.0.0.1:8000/rest-auth/user/`,
            {
                headers: { 'Content-Type': 'application/json' }
            }
        )
            .then(res => {
                console.log(res)
            }).catch(Error => {
                console.log(Error)
            })

which returns the same error as before. How should I execute this request successfully?

1
are you getting desired result from same URL in browsable API ? - Anoop K George
since http://127.0.0.1:8000/rest-auth/user/ requires authentication it redirects me to login page http://127.0.0.1:8000/rest-auth/login/ once that is successful it return the desired data. - Chinmay Dali
try console.log(token) in axios function, make sure that you passes token - Anoop K George
In the header section try headers: { 'Authorization': "Token " + localStorage.getItem('token') }, capital Token instead token - Anoop K George
I have set the 'token' in localStorage in this way; I am certain that passing the token is correct. - Chinmay Dali

1 Answers

1
votes

The axios POST method is correct, however make sure you passes the token

let tokentoserver = localStorage.getItem('token');
console.log(tokentoserver);

axios.get(`http://127.0.0.1:8000/rest-auth/user/`,
            {
                headers: { 'Authorization': "Token " tokentoserver }
            }
        ).then(res => {
            console.log(res)
        }).catch(Error => {
            console.log(Error)
        })

I have removed the + sign you used to add token together