Запрещено (CSRF-куки не установлены.) Django и Angular
Я получаю ошибку CSRF cookie not set
вот мой файл angular coponent.ts
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)
}
)
}
метод getCookies в component.ts
private getCookies(name:string):any{
const cookieValue = document.cookie.match('(^|;)\\s*' + name +
'\\s*=\\s*([^;]+)');
return cookieValue ? cookieValue.pop() : '';
}
Здесь 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)
вот мой settings.py
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
ALLOWED_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
Разве мой бэкэнд не получает cookie? Я пытаюсь создать csrftoken
в angular, а затем позволить боту отправить мне сообщение из telegram.
Пожалуйста, помогите мне решить эту проблему.