这是一个基本的Angular 4
应用程序,Django Rest framework
作为后端。我正在使用JWT
令牌进行身份验证。当我单击登录按钮时,此错误会显示。我找不到为什么会这样。我是Typescript
和Angular 4
的新手,希望有人能解决这个问题。我试图改变signInComponent.html
但问题没有解决
** SignInComponent.ts **
import { NgForm } from '@angular/forms/src/directives';
import { Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { UserService } from '../../services/user.service';
@Component({
selector: 'app-sign-in',
templateUrl: './sign-in.component.html',
styleUrls: ['./sign-in.component.css']
})
export class SignInComponent {
token=null ;
formError: string;
submitting = false;
constructor(private router:Router, private authService:UserService) { }
onSubmit(signInForm: NgForm ) {
if (signInForm.valid) {
console.log('submitting...', signInForm);
this.submitting = true;
this.formError = null;
this.authService.login(signInForm.value.username,
signInForm.value.password)
.subscribe((data) => {
this.token=data['data'];
console.log( this.token['token'])
this.authService.saveJWT(this.token['token']);
this.authService.isAuthenticated =true;
this.router.navigate(['/auth']);
},
(err)=> {
this.submitting = false;
console.log('got error: ', err);
this.formError = err;
this.router.navigate(['/login']);
}
);
}
this.authService.ping().subscribe((data) => {
console.log('got token yeeh: ');
console.log(this.authService.getJwt());
},
);
}
}
** SignInComponent.html **
<div class="sign-in-form">
<img src="./assets/logo.jpg" width="320" />
<h4>Sign In</h4>
<form #signInForm="ngForm" (ngSubmit)="onSubmit(signInForm)" novalidate>
<div class="form-group">
<input class="form-control" name="username" required placeholder="User Name"
ngModel #username="ngModel" />
<div [hidden]="username.valid || username.pristine" class="alert alert-
danger">
User Name is required.
</div>
</div>
<div class="form-group">
<input class="form-control" name="password" required type="password"
placeholder="Password" ngModel #password="ngModel"/>
<div [hidden]="password.valid || password.pristine" class="alert alert-
danger">
Password is required.
</div>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="rememberMe" ngModel /> Remember Me
</label>
</div>
<div *ngIf="formError" class="alert alert-danger">
{{ formError }}
</div>
<div *ngIf="!submitting">
<button type="submit" class="btn btn-primary">Sign In</button>
</div>
<div *ngIf="submitting">
<p class="message">Signing In...</p>
</div>
</form>
</div>
** AuthService.ts **
import { any } from 'codelyzer/util/function';
import { Injectable, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import { HttpHeaders } from '@angular/common/http';
@Injectable()
export class UserService {
isAuthenticated = false;
constructor(private router: Router ,private http:HttpClient ) {
}
saveJWT(strToken: string): any {
localStorage.setItem('JWT',strToken);
}
login(username: string, password: string):Observable<any> {
let headers =new HttpHeaders();
var body = "username="+username+"&password="+password;
headers = headers.set("Content-Type", "application/x-www-form-urlencoded");
return this.http.post('http://nucore.ddns.net:800/v1/user/login', body, {
headers:headers});
}
getJwt():string
{
return localStorage.getItem('JWT');
}
ping():Observable<any> {
return this.http.get('https://jsonplaceholder.typicode.com/users')
}
logOut() {
// remove user from local storage to log user out
localStorage.removeItem('JWT');
this.isAuthenticated = false;
this.router.navigate(['/login']);
}
}
答案 0 :(得分:3)
将此作为答案发布,因为我花了一整天的时间试图在从Angular 2迁移到Angular 6时解决这个问题,并且我确定有人有同样的错误。
问题是http拦截器将auth令牌添加到登录请求,此时auth令牌为null。因此,请确保authinterceptor不会尝试将令牌添加到登录请求
答案 1 :(得分:0)
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {Observable} from 'rxjs';
import {Http, Headers} from '@angular/http';
@Injectable()
export class UserService {
isAuthenticated = false;
constructor(private router: Router, private http: Http) {
}
saveJWT(strToken: string): any {
localStorage.setItem('JWT', strToken);
}
login(username: string, password: string): Observable<any> {
const head = new Headers();
const body = 'username=' + username + '&password=' + password;
head.set('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post('http://nucore.ddns.net:800/v1/user/login', body, {
headers: head
});
}
getJwt(): string {
return localStorage.getItem('JWT');
}
ping(): Observable<any> {
return this.http.get('https://jsonplaceholder.typicode.com/users')
}
logOut() {
// remove user from local storage to log user out
localStorage.removeItem('JWT');
this.isAuthenticated = false;
this.router.navigate(['/login']);
}
}