【发布时间】:2020-01-28 18:03:35
【问题描述】:
我已经尝试解决这个问题几个小时了,如果可以的话,请帮助我。
当我尝试在我的 React 应用程序中使用 axios 向我的 DRF Rest API 发出 get 请求时,它返回 403。
App.js:
axios
.get(API_POSTS, {
headers: {
Authorization: `Token 27dbb4dd8299792c8c52022f829da4ecec22f437`
}
})
.then(res => {
console.log("Success");
})
.catch(error => {
console.log(error);
});
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
# 3rd-party apps
'rest_framework',
'rest_framework.authtoken',
'allauth',
'allauth.account',
'allauth.socialaccount',
'rest_auth',
'rest_auth.registration',
'corsheaders',
# Local
'posts.apps.PostsConfig',
'users.apps.UsersConfig',
]
CORS_ORIGIN_WHITELIST = [
'http://localhost:3000',
]
# Rest Framework
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication'
],
}
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
)
SITE_ID = 1
REST_AUTH_REGISTER_SERIALIZERS = {
'REGISTER_SERIALIZER': 'users.serializers.CustomRegisterSerializer',
}
我有一个只有经过身份验证的用户才能看到的posts 端点。
从我的 React APP 中登录后,生成了这个令牌。 (现在使用纯文本,因为我正在测试)
所以,当我尝试使用它发出 get 请求时,它会返回以下错误:
Error: Request failed with status code 403
at createError (createError.js:17)
at settle (settle.js:19)
at XMLHttpRequest.handleLoad (xhr.js:60)
为什么会这样? 我是否需要通过标头发送更多信息?我已阅读其他问题和文档,但找不到答案。
谢谢。
【问题讨论】:
-
您是否尝试过使用 postman 之类的工具检查您的 API 是否正常工作?
-
你好。是的,我有,它适用于 Postman 和 Django Rest Framework 中的内置可浏览 API。编辑:它也给了我 403 和 Postman。
-
如果邮递员也出现错误,因为问题出在 API 而不是反应应用程序。
-
您知道错误可能是什么吗?
-
对不起,我对 Django 不熟悉,希望您能尽快得到答复。
标签: reactjs django-rest-framework token