我正在使用Django和AngularJs2建立一个网站。
当我创建登录表单然后提交表单时,Django显示错误:
禁止(CSRF令牌丢失或不正确。)
我知道Django希望我添加一个CSRF令牌,但我不知道如何。
更新 这是user.service.ts:
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
@Injectable()
export class UserService {
private loggedIn = false;
constructor(private http: Http) {
this.loggedIn = !!localStorage.getItem('auth_token');
}
login(email:string, password:string) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http
.post(
'/accounts/login',
JSON.stringify({ email, password }),
{ headers }
)
.map(res => res.json())
.map((res) => {
if (res.success) {
/* localStorage.setItem('auth_token', res.auth_token);
this.loggedIn = true; */
console.log(res);
}
return res.success;
});
}
logout() {
localStorage.removeItem('auth_token');
this.loggedIn = false;
}
isLoggedIn() {
return this.loggedIn;
}
}
login.component.ts:
// login.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { UserService } from './user.service';
@Component({
selector: 'login',
template: `...`
})
export class LoginComponent {
constructor(private userService: UserService, private router: Router) {}
onSubmit(email, password) {
this.userService.login(email, password).subscribe((result) => {
if (result) {
this.router.navigate(['']);
}
});
}
}
答案 0 :(得分:0)
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def your_view(request):
pass
或者如果您想拥有csrf,请使用您的角度
发送它$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$httpProvider.defaults.xsrfCookieName = 'csrftoken';