I am attempting to send data from my React frontend to a Django backend and trigger a function. I'm developing a Django REST API using Django Rest Framework, and I've set up a view in the calculator app to handle POST requests. The objective of the calculator view is simply concatenate text from frontend:
#app/calculator/views.py
from django.http import JsonResponse
def concat_text(request):
if request.method == 'POST':
received_text = request.POST.get('text', '')
result = received_text + ' =)'
print(result)
return JsonResponse({'result': result})
else:
return JsonResponse({'error': 'Only POST requests are allowed'})
However, when I make a request from my React frontend, I'm receiving a 403 error (Forbidden). I am sending the text value via frontend by:
const handleButtonClick = async (e) => {
e.preventDefault();
try {
const response = await fetch(`${URL}/calculator/calculator/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ text }),
});
The URL is simply the "http://localhost:8000". I have also defined the calculator urls:
#app/calculator/urls.py
from django.urls import path
from .views import concat_text
urlpatterns = [
path('calculator/', concat_text),
]
My app urls:
#app/urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView
from core import views as core_views
urlpatterns = [
path('admin/', admin.site.urls),
path('health-check/', core_views.health_check, name='health-check'),
path('schema/', SpectacularAPIView.as_view(), name='api-schema'),
path(
'',
SpectacularSwaggerView.as_view(url_name='api-schema'),
name='api-docs',
),
path('user/', include('user.urls')),
path('wallet/', include('wallet.urls')),
path('simulation/', include('simulation.urls')),
path('calculator/', include('calculator.urls')),
]
The error indicates a CSRF problem
Forbidden (CSRF cookie not set.): /calculator/calculator/