我正在使用Angular 2和Django 1.10.6。我创建了一个post方法。从前端发送请求后,显示CSRF令牌丢失或不正确。
user.html
<form #f="ngForm" (ngSubmit)="createUser(f.value, f.valid,f)" novalidate>
....
</form>
Angular2组件
createUser(model: User, isValid: boolean, f: any) {
// check if model is valid
// if valid, call API to save customer
if (isValid) {
this.userCreateService.createUser(model).subscribe(
res => {
this.success = "User Create Success";
this.user = new User();
this.errorMsg=null
},
err => {
this.errorMsg = err;
this.success=null;
});
}
}
这是我的Angular2服务
@Injectable()
export class UserCreateService {
constructor(private http: Http) { }
// private instance variable to hold base url
private userCreateUrl = '/api/user/users/';
// Add a new User
createUser(body: Object): Observable<User> {
let bodyString = JSON.stringify(body); // Stringify payload
let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
let options = new RequestOptions({ headers: headers }); // Create a request option
return this.http.post(this.userCreateUrl, body, options) // ...using post request
.map(this.extractData) // ...and calling .json() on the response to return data
.catch(this.handleError); //...errors if any
}
答案 0 :(得分:0)
在问了几个问题之后,我就这样解决了我的问题。 在角度2服务中创建方法。
getCookie(name) {
let value = "; " + document.cookie;
let parts = value.split("; " + name + "=");
if (parts.length == 2)
return parts.pop().split(";").shift();
}
并替换
let headers = new Headers({
'Content-Type': 'application/json'}); // .Set content type to JSON
到
let headers = new Headers({
'Content-Type': 'application/json',
'X-CSRFToken': this.getCookie('csrftoken')
}); // ... Set content type to JSON
在createUser()角度服务方法中。