【问题标题】:django-rest-auth get username from rest-auth/userdjango-rest-auth 从 rest-auth/user 获取用户名
【发布时间】:2020-10-03 00:14:43
【问题描述】:

我想检索用户详细信息以显示已登录用户的用户名 我需要从 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)

同样在上面的代码中,我还以以下方式指定了标题 headers: { '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)
            })

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

【问题讨论】:

  • 您是否从可浏览 API 中的相同 URL 获得所需结果?
  • 因为http://127.0.0.1:8000/rest-auth/user/ 需要身份验证,它会将我重定向到登录页面http://127.0.0.1:8000/rest-auth/login/,一旦成功,它就会返回所需的数据。
  • 在axios函数中试试console.log(token),确保你传递了token
  • 在标题部分尝试标题:{ 'Authorization': "Token " + localStorage.getItem('token') },大写 Token 代替 token
  • 我已经通过这种方式在localStorage中设置了'token';我确定传递令牌是正确的。

标签: django reactjs django-rest-framework axios django-rest-auth


【解决方案1】:

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

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

【讨论】:

  • 我猜它起作用了,但又给了我两个错误; (在 和 之间添加一个逗号)这两个错误是:- 第一个 Access to XMLHttpRequest at 'http://127.0.0.1:8000/rest-auth/user/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field tokentoserver is not allowed by Access-Control-Allow-Headers in preflight response. 第二个:GET http://127.0.0.1:8000/rest-auth/user/ net::ERR_FAILED 我已将我的 cors 标头设置为 CORS_ORIGIN_ALLOW_ALL = True
  • 我认为禁止从前端调用用户详细信息它只能在可浏览的API中工作;
  • 我不知道你的 view.py 是如何处理 GET 请求的,什么都禁止
  • 我正在使用 django-rest-auth 的默认用户模型,就像在这个 github.com/Chinmay-395/django-rest-auth/blob/master/rest_auth/…
猜你喜欢
  • 2019-07-10
  • 1970-01-01
  • 1970-01-01
  • 2022-07-04
  • 1970-01-01
  • 1970-01-01
  • 2019-01-28
  • 2016-07-14
  • 1970-01-01
相关资源
最近更新 更多