我正在尝试使用 axios 从/rest-auth/user/页面获取信息。这是我的功能:
export const fetchUser = () => {
const token = localStorage.getItem('token');
return dispatch => {
dispatch(fetchUserPending());
axios.get('http://localhost:8000/api/v1/rest-auth/user/', {headers: { 'authorization': `Bearer ${token}`}})
.then(response => {
const user = response.data;
dispatch(fetchUserFulfilled(user));
})
.catch(err => {
dispatch(fetchUserRejected(err));
})
}
}
它使用我从登录中获得的 django token ,该 token 存储在 localStorage 中。我收到错误状态 403,未提供身份验证凭据。我尝试编辑我的 django settings.py 文件以包含
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
然后我收到未经授权的错误代码 401。谁能指导我正确的方向?谢谢!
最佳答案
默认情况下 rest_framework.authentication.TokenAuthentication
使用关键字 Token
而不是 Bearer
。调用应该是:
axios.get('http://localhost:8000/api/v1/rest-auth/user/', {headers: { 'Authorization': `Token ${token}`}})
关于Django rest-auth Token 认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53192681/