【问题标题】:How do I send cookies in a request from an Angular 2+ application to a Django backend where I access them as cookies?如何将来自 Angular 2+ 应用程序的请求中的 cookie 发送到我作为 cookie 访问它们的 Django 后端?
【发布时间】: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


【解决方案1】:

如果您谈论 CSRF 以允许您的 POST 到您的后端,您可以在将数据发送到 django 时在您的标头中传递它

检查这个例子:

https://docs.djangoproject.com/en/2.0/ref/csrf/#setting-the-token-on-the-ajax-request

http://django-angular.readthedocs.io/en/latest/csrf-protection.html

【讨论】:

  • 这对我不起作用(Django 仍然记录“CSRF cookie not set”)(见上面的编辑)
【解决方案2】:

确保您在每个请求中都有 cookie

  1. 我将 ngx-cookie-service 添加到我的项目 https://github.com/7leads/ngx-cookie-service#readme

  2. 然后我做一个拦截器csrf.interceptor.ts

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
import { Observable } from 'rxjs';

@Injectable()
export class CsrfInterceptor implements HttpInterceptor {
    csrfToken: any;

    constructor(
        private cookieService: CookieService
    ) {
        this.csrfToken = this.cookieService.get('csrftoken');
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (this.csrfToken) {
            const addCsrf = req.clone({
                headers: req.headers.set('X-CSRFToken', this.csrfToken)
            });
            return next.handle(addCsrf);
        } else {
            return next.handle(req);
        }
    }
}

最后在你的 app.module 中你需要提供拦截器:

// angular core
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { CookieService } from 'ngx-cookie-service';

// services
// components
@NgModule({
    declarations: [
        ...
    ],
    imports: [
        HttpClientModule
    ],
    providers: [
        CookieService,
        {
            provide: HTTP_INTERCEPTORS,
            useClass: CsrfInterceptor,
            multi: true
        }
    ],
    bootstrap: [
        AppComponent
    ]
})
export class AppModule { }

【讨论】:

  • 看起来这获取了一个从 Django 发送的 cookie 并将一个标头发送回 Django,但没有将 cookie 设置为 Django 可访问的实际 cookie。我希望这是一个解决方案,但我认为 Django 仍然会抱怨“未设置 CSRF cookie”。
最近更新 更多