2017-04-06 62 views
0

我正在使用Angular 2和Django 1.10.6。我創建了一個post方法。在從前端發送請求之後,顯示CSRF令牌丟失或不正確。CSRF令牌在角度2中丟失或不正確2 + DJango 1.10.6

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

請同時提供django的views.py – Bijoy

回答

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

()角服務方法。

相關問題