Проблема CSRF при вызове api из фронтенда [закрыто]
Create_admin.py
def create_agent(request):
if request.method == 'POST':
name = request.POST.get('name')
username = request.POST.get('username')
password = request.POST.get('password')
if name and username and password:
agent = Agent.objects.create(name=name, username=username, password=password)
return JsonResponse({'status': 'success'})
return JsonResponse({'status': 'failed'}, status=400)
return render(request, 'superadmin/create_agent.html')
@user_passes_test(is_super_admin)
def fetch_payments(request):
if request.method == 'GET':
payments = Payment.objects.all().values() # Fetch all payment data
return JsonResponse(list(payments), safe=False)
class PaymentListView(APIView):
def get(self, request):
payments = Payment.objects.all()
data = [
{
"id": payment.id,
"agent_name": payment.agent_name,
"amount": payment.amount,
"payment_link": payment.payment_link,
"status": payment.status,
"created_at": payment.created_at,
}
for payment in payments
]
return JsonResponse(data, safe=False)
create_admin.jsx
const handleCreateAgent = async (e) => {
e.preventDefault();
const csrfToken = getCSRFToken(); // Get the CSRF token
try {
const response = await axios.post('http://127.0.0.1:8000/api/superadmin/create-agent/', {
username,
password,
name: agentName,
}, {
headers: {
'X-CSRFToken': csrfToken, // Include the CSRF token in the headers
},
withCredentials: true
});
setMessage('Agent created successfully!');
setUsername('');
setPassword('');
setAgentName('');
} catch (error) {
console.error('There was an error creating the agent!', error);
setMessage('Failed to create agent.');
}
};
Forbidden (CSRF cookie not set.): /api/superadmin/create-agent/
[13/Aug/2024 12:32:07] "POST /api/superadmin/create-agent/ HTTP/1.1" 403 2869
Это ошибка, которую я получаю при вызове api из фронтенда.Проблема в том, что я уже установил cookies
CORS_ALLOW_CREDENTIALS = True
CSRF_COOKIE_HTTPONLY = True
CSRF_COOKIE_SECURE = True # Set to True in production
SESSION_COOKIE_SECURE = False # Set to True in production
Вот как я устанавливаю cookies.