I am gettig error CSRF cookie not set
here is my angular coponent.ts file
sendMessage(nick:string) {const formData = new FormData();this.nickname = nick;formData.append('nickname',this.nickname);const headers = new HttpHeaders({'X-CSRFToken':this.getCookies('csrftoken')});this.http.post('http://127.0.0.1:8000/api/send/', formData, {headers:headers, withCredentials:true}).subscribe( (response:any) => { if(response.success){ this.messageStatus = 'Message sent succesfully'; } else { this.messageStatus = 'Failed to send message'; } }, error => { this.messageStatus = 'Failed to message' console.log('erorr is ',error) console.log(this.getCookies('csrftoken')) console.log(headers) } )}
method getCookies in component.ts
private getCookies(name:string):any{ const cookieValue = document.cookie.match('(^|;)\\s*'+ name +'\\s*=\\s*([^;]+)'); return cookieValue ? cookieValue.pop() : '';}
Here is views.py django
def send_message_to_telegram(request): if request.method == 'POST': telegram_nickname = request.POST.get('nickname') # Replace 'YOUR_BOT_TOKEN' with your actual Telegram bot token bot_token = 'My _ token' bot_chat_id = '789829434' # Replace with your bot's chat ID message = f"Hello, @{telegram_nickname}! This is a message from our bot." # Sending message via Telegram Bot API url = f"https://api.telegram.org/bot{bot_token}/sendMessage" payload = {'chat_id': bot_chat_id,'text': message } response = requests.post(url, json=payload) if response.ok: return JsonResponse({'success': True, 'message': 'Message sent successfully'}) else: return JsonResponse({'success': False, 'message': 'Failed to send message'}) else: return JsonResponse({'success': False, 'message': 'Method not allowed'}, status=405)
here is my settings.py
CORS_ORIGIN_ALLOW_ALL = TrueCORS_ALLOW_CREDENTIALS = TrueALLOWED_HOSTS = ["http://locallhost:4200","127.0.0.1"]CORS_ALLOW_METHODS = ("DELETE","GET","OPTIONS","PATCH","POST","PUT",)CORS_ALLOW_HEADERS = ("accept","authorization","content-type","user-agent","x-csrftoken","x-requested-with",)CSRF_TRUSTED_ORIGINS = ['http://localhost:4200', ]CSRF_COOKIE_SECURE = True
Isn't my backend get cookie? I am trying to create csrftoken
in angular then let the bot send me message from telegram.
Please help me to solve this problem.