我使用DjangoREST,React和Redux创建了一个应用程序,该应用程序已部署在Heroku上,但出现服务器错误(500)。我使用allauth进行令牌身份验证。每个网址在开发中都能正常工作,但在生产中却无法正常工作。
我通过 / rest-auth / login / 网址成功获得了令牌,并且令牌也成功地作为“ Authorization”:令牌 token 在标头中传递em> 。
这是我也得到的错误console.log错误-
urls.py
from django.contrib import admin
from django.urls import path, include, re_path
from todo import views
urlpatterns = [
path('admin/', admin.site.urls),
path('api/todos/', views.TodoList.as_view()),
path('api/todos/<int:pk>/', views.TodoDetail.as_view()),
path('rest-auth/', include('rest_auth.urls')),
path('rest-auth/registration/', include('rest_auth.registration.urls')),
path('api/user/', views.UserAPI.as_view()),
re_path(r'^', views.FrontendAppView.as_view())
]
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', 'dj-react-todo.herokuapp.com']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'todo',
'corsheaders' ,
'rest_framework',
'rest_framework.authtoken',
'rest_auth' ,
'allauth',
'allauth.socialaccount' ,
'allauth.account',
'rest_auth.registration',
]
SITE_ID = 1
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'backend.urls'
WSGI_APPLICATION = 'backend.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'build')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication'
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'build', 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = (
'content-type' ,
'xsrfheadername' ,
'xsrfcookiename',
'X-CSRFTOKEN'
)
CSRF_COOKIE_NAME = "XCSRF-TOKEN"
ACCOUNT_EMAIL_VERIFICATION = "none"
ACCOUNT_AUTHENTICATION_METHOD = 'username'
ACCOUNT_EMAIL_REQUIRED = False
views.py
class TodoList(APIView):
serializer_class = TodoSerializer
authentication_classes = (authentication.TokenAuthentication,)
permission_classes = (permissions.IsAuthenticated,)
def get(self, request, format=None):
todos = Todo.objects.filter(user=request.user)
serializer = TodoSerializer(todos, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = TodoSerializer(data=request.data)
if serializer.is_valid():
serializer.save(user=request.user)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializers.py
from rest_framework import serializers
from .models import Todo
from django.contrib.auth.models import User
class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = ('id', 'user', 'title', 'description', 'completed', 'deadline', 'crucial')
def create(self , validated_data):
return Todo.objects.create(**validated_data)
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email')
这是我创建actionCreator来获取用户创建的所有待办事项的方式-
import axios from 'axios' ;
import { ADD_TODO, FETCH_TODOS, DELETE_TODO, TOGGLE_CHECKBOX, CRUCIAL_TODO} from './types' ;
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios.defaults.xsrfCookieName = "XCSRF-TOKEN";
axios.defaults.headers.post['Access-Control-Allow-Methods'] = 'PATCH, DELETE, POST, GET, OPTIONS';
export const getTodos = () => dispatch => {
const token = localStorage.getItem('token')
const config = {
'headers': {
'Authorization': `Token ${token}` ,
}
}
if (token){
axios.get('https://dj-react-todo.herokuapp.com/api/todos/', config)
.then(res => {
dispatch({
type: FETCH_TODOS ,
payload: res.data
});
})
.catch(err => console.log(err))
}
}
我不明白为什么会收到此错误,我已经传递了令牌,并且也通过该令牌获得了经过身份验证的用户。 我检查了heroku日志,它还显示500服务器错误。