【发布时间】:2026-01-14 17:55:02
【问题描述】:
Angular 在浏览器中设置 cookie,但是当我向 Django 发出 POST 请求时,request.COOKIES 在 Django 视图中为空。我需要将 CSRF cookie 发送回 Django,作为 cookie 存储和访问。
注意:简单地在如下标头中发送 CSRF(或使用任何其他标头技术)不起作用(Django 仍会记录“禁止:CSRF cookie 未设置”)
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { SharedService } from '../../shared.service';
import { CookieService } from 'ngx-cookie-service';
@Injectable({
providedIn: 'root'
})
export class EmailService {
// http options used for making any writing API calls with csrf token
private httpOptions: any;
csrfToken;
constructor(private http: HttpClient, private cookieService: CookieService) {
// Set the csrf token
this.http.get(SharedService.contactEmailUrl).subscribe((data) => (this.csrfToken = data['csrfToken']), (error1) => console.log(error1));
}
sendMailgunContactMessage(payload) {
// Configure CSRF token header options
this.httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRFToken': this.csrfToken,
'x-csrftoken': this.csrfToken,
'X-XSRF-TOKEN': this.csrfToken,
'XSRF-TOKEN': this.csrfToken,
'X-CSRF': this.csrfToken,
csrfmiddlewaretoken: this.csrfToken,
csrftoken: this.csrfToken
}),
withCredentials: true
};
let body = {
csrfmiddlewaretoken: this.csrfToken,
content: payload
};
this.cookieService.set('csrfcookie', this.csrfToken);
return this.http.post(SharedService.contactEmailUrl, body, this.httpOptions);
}
}
【问题讨论】:
-
你需要发送什么cookie...csrf?
-
是的,我需要发送 csrf
标签: django angular cookies angular6