Chinmay Dali
Chinmay Dali

Reputation: 375

django-rest-auth get username from rest-auth/user

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?

Upvotes: 1

Views: 996

Answers (1)

Anoop K George
Anoop K George

Reputation: 1755

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

Upvotes: 1

Related Questions