Angular2身份验证:POST请求有问题吗?

时间:2017-04-17 23:13:45

标签: json angular http authentication post

您好我正在尝试对用户进行身份验证,一旦服务器提供了用户的信息,我想使用该用户的信息。

但由于某些原因,即使我在登录过程中没有任何错误,我可以从开发人员的工具中看到POST请求已成功,我无法在localStorage中设置currentUser (如果我在console.log中给我null)

我做错了什么?

这是我的身份验证服务。

export class AuthenticationService {

constructor(private http: Http, private router: Router) { }

login(email: string, password: string): Observable<User>{
    const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
    headers.append('Access-Control-Allow-Headers', 'Content-Type');
    headers.append('Access-Control-Allow-Methods', 'post');
    headers.append('Access-Control-Allow-Origin', '*');
    headers.append("X-Requested-With", "XMLHttpRequest");

    let options = new RequestOptions({ headers: headers });

    let body = new URLSearchParams();
    body.set('email', email);
    body.set('password', password);

    return this.http.post(`${environment.baseurl}` + '/api/v2/member/login', body, options)
        .map(this.extractData)
        .catch(this.handleError);
}

private extractData(res: Response) {
    let user = res.json();
    if (user && user.token) {
        localStorage.setItem('currentUser', JSON.stringify(user));
    }
    return user.data || {}; 
}

logout() {
    // remove user from local storage to log user out
    localStorage.removeItem('currentUser');

}

private handleError(error: any) {

    if (error.status === 401) {
        return Observable.throw(error.status);
    } else {
        return Observable.throw(error.status || 'Server error');
    }
}
 }

这是我的登录组件

export class LoginPageComponent implements OnInit {

constructor(private location: Location,
    private route: ActivatedRoute,
    private router: Router,
    private authenticationService: AuthenticationService,
    private alertService: AlertService) {
     }

model: any = {};
loading = false;
returnUrl: string;

error = '';

ngOnInit() {
    // get return url from route parameters or default to '/'
    this.returnUrl = this.route.snapshot.queryParams['main'] || '/';
}

currentUser: User;

login() {
    this.loading = true;
    this.authenticationService.login(this.model.email, this.model.password)
        .subscribe(
        data => {
            this.currentUser = data;
            this.router.navigate([this.returnUrl]);
        },
        error => {
            this.error = "Wrong ID or PW";
            this.loading = false;
        });
}


backClicked() {
    this.location.back();
}
}

这是我的家庭组件

export class MainComponent {

onClick() {
  this.auth.logout() //if user clicks logout button
}

currentUser: User;
users: User[] = [];

items: Object[] = [];

constructor(private authguard: AuthGuard, private auth:AuthenticationService) {
  this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
  console.log(localStorage.getItem('currentUser')); //Printing null
}

}

用户信息的模型就是这个。

export interface User {
birthday: number;
email:string;
genderType:string;
memberType: string;
name: string;
phone: string;

}

enter image description here

接收什么

为什么打印为空? 谢谢!

1 个答案:

答案 0 :(得分:0)

你犯的错误

  1. 将电子邮件和密码作为URLSearchParams传递。
  2. 您正在将所有标题添加到您的登录方法中,这是不必要的
  3. 该服务应包含以下方法

        login(body: any, options?: RequestOptionsArgs): Observable<Response> {
                return this.http.post('loginUrl', body);
            }
    

    组件应包含以下代码

    login() {
    
        let user ={
        email : this.model.email
        password : this.model.password)
        }
        this.loading = true;
        this.authenticationService.login(user)
            .subscribe(data => {
                this.authenticationService.extractData(data);///call to store token in the localstorage
                this.router.navigate([this.returnUrl]);
            },
            error => {
                this.error = "Wrong ID or PW";
                this.loading = false;
            });
    }