I faced some problem using react and django.
When I made a http request to django server, I got 500 Internal Server Error.
My code looks like.
urls.py
from usercontrol.views import *
urlpatterns = [
path('admin/', admin.site.urls),
path('auth/', UserView.as_view(), name="something")
]
usercontrol/views.py
from http.client import HTTPResponse
from django.shortcuts import render
from rest_framework.views import APIView
from . models import *
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, AllowAny
# Create your views here.
class UserView(APIView):
permission_classes = [AllowAny]
def get(self, request):
if request.user.is_authenticated:
print ("HELO")
return HTTPResponse("Hello")
def post(self, request):
return HTTPResponse("Hello")
React Code
axios.get("http://localhost:8000/auth/")
.then((res) => {
console.log(res);
})
.catch((err) => {});
Why do I get 500 Internal Server Error? Please help me to fix this error.
Need to install corsheaders
in django.
pip install django-cors-headers
Also need to add following configuration in settings.py
and add corsheaders
in Installed_apps
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = [
"http://127.0.0.1:3000",
"http://127.0.0.1",
"http://localhost:3000",
"http://localhost"
]
ALLOWED_HOSTS = ['*',
"http://127.0.0.1:3000",
"http://127.0.0.1",
"http://localhost:3000",
"http://localhost"
]
While running react server make sure backend django server is also running.