I am making a website using Django and AngularJs2.
When I created the login form then submit form, Django shows an error:
forbidden (CSRF token missing or incorrect.)
I know Django wants me to add a CSRF token, but I don't know how.
UPDATE this is 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(['']);
}
});
}
}