首页 > 解决方案 > django-rest-auth 从 rest-auth/user 获取用户名

问题描述

我想检索用户详细信息以显示登录用户的用户名我需要从 django-rest-auth 的“ http://127.0.0.1:8000/rest-auth/user/ ”获取用户名我是 reactjs 的新手,并尝试了成功但无法通过的身份验证。

到目前为止我已经尝试过了

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)
        })

返回禁止的 403 错误;

错误

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

同样在上面的代码中,我还以以下方式指定了标题:{ 'Authorization': "token key_from_DRF" }但没有运气

我也试过这个

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)
            })

它返回与以前相同的错误。我应该如何成功执行此请求?

标签: djangoreactjsdjango-rest-frameworkaxiosdjango-rest-auth

解决方案


axios POST 方法是正确的,但是请确保您传递了令牌

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)
        })

我删除了+ 你用来一起添加令牌的标志


推荐阅读