如何使用 React 从 DRF 获取不记名令牌?

How do I get bearer token from DRF using React?

我有一个使用 DRF 构建的后端,以及使用 React 和 axios 构建的前端。一旦有人登录,服务器就会发出一个 csrf 令牌和会话 ID。无论如何我可以提取服务器生成的 Bearer 令牌吗?

您需要先安装rest framework authtoken,

INSTALLED_APPS = [
    ...
    'rest_framework.authtoken'
]

然后将其包含在 settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        )
    }

然后登录并获取密钥为-

axios
  .post("https://www.example.com/rest-auth/login/", {
    username: username,
    password: password,
  }).then((res) => {
      const token = res.data.key;
    })