来自Django的Angular 4 CLI中的CSRF令牌

时间:2018-04-27 16:24:26

标签: django angular

我使用Angular,Node,Express和Postgres创建了一个全栈应用: https://github.com/shivkiyer/database-app

现在我正在尝试通过在后端而不是Node JS上使用Django重复项目来学习Django。整个代码在这里: https://github.com/shivkiyer/djangoangular

我无法在Angular中提取Django发送的CSRF令牌,以便在提交POST表单时将其发回。

在Django中,我有两个观点:

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from . import models, forms

# Create your views here.

def basic_list(request):
    print(request)
    customer_list = []
    for customer_item in models.Customer.objects.all():
        customer_list.append({
            "first_name": customer_item.first_name,
            "last_name": customer_item.last_name,
            "city": customer_item.city
        })
    print(customer_list)
    return JsonResponse(customer_list, safe=False)

def empty_form(request):
    print(request)
    return HttpResponse("Form received")

在我的settings.py文件中,我启用了“django.middleware.csrf.CsrfViewMiddleware”。我查看了Django文档: https://docs.djangoproject.com/en/2.0/ref/csrf/

我尝试在settings.py文件中添加几个选项:

CSRF_USE_SESSIONS = True
CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = (
    'content-type',
    'HTTP_X_CSRFTOKEN'
)

CORS_EXPOSE_HEADERS = [
    'content-type',
    'HTTP_X_CSRFTOKEN']

My Angular组件有:

import { Component, OnInit } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';
  sample_form: FormGroup;
  server_token: any;

  constructor(private http: Http) {
    this.sample_form = new FormGroup({
      'first_name': new FormControl(null),
      'last_name': new FormControl(null)
    });
  }

  ngOnInit() {}

  viewCustomers() {
    this.http.get('http://127.0.0.1:8000/list/')
        .subscribe((response: Response) => {
          console.log(response.headers.keys());
          this.server_token = response.headers.get('http_x_csrftoken');
          console.log(response.headers.get('http_x_csrftoken'));
          console.log(response.json());
        });
  }

  send_sample_form() {
    let my_headers = new Headers({'x-csrftoken': this.server_token});
    this.http.post('http://127.0.0.1:8000/emptyform/',
          {'my_form': this.sample_form.value},
          {headers: this.server_token})
          .subscribe(
            (response) => {
              console.log(response.headers.keys());
              console.log(response);
            }
          );
  }

}

我无法从标头中提取CSRF令牌。命令:     的console.log(response.headers.keys());

仅显示标题内容类型。如何获取此令牌并在POST请求中将其发送回Django。当我在settings.py中禁用'django.middleware.csrf.CsrfViewMiddleware'时,它可以工作。所以没有其他跨站点问题。

提前致谢。

0 个答案:

没有答案