繁体   English   中英

登录帖子请求生成错误

[英]Login post request generates error

我正在尝试使用angular实现一个简单的登录系统。 当前,如果我尝试使用正确的详细信息登录,则可以成功获取访问令牌并将其存储到本地存储中。

但是,尝试使用错误的详细信息登录会产生401未经授权的错误,以响应发布请求。 除了像现在一样在响应中查找参数之外,还有另一种方法来测试登录失败吗?

auth.service.ts

import { Injectable } from '@angular/core';
import { HttpRequest, HttpClient, HttpHeaders, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class AuthService {
  public token: string;
  constructor(private http: HttpClient) {
    var currentUser = JSON.parse(localStorage.getItem('currentUser'));
        this.token = currentUser && currentUser.id;
   }

   public login(username:string, password:string){
    return this.http.post<any>('http://localhost:3000/api/v1/users/login', {username:username, password:password})
      .map((res) => {
        console.log(res);
        let token = res.id ;
        let id = res.userId ;
        // login successful if there's a jwt token in the response
        if (token) {
          this.token = token;
            // store username and jwt token in local storage to keep user logged in between page refreshes
            localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token, id:id }));
            // return true to indicate successful login
            return true;
        } else {
            // return false to indicate failed login
            return false;
        }
    });
  }

登录-form.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AlertService } from '../../_services/alert.service';
import { AuthService } from '../../_services/auth.service';

@Component({
  selector: 'app-login-form',
  templateUrl: './login-form.component.html',
  styleUrls: ['./login-form.component.css'],
  providers: [AuthService, AlertService]
})

export class LoginFormComponent implements OnInit {
  model: any = {};
  loading = false;
  error = '';
  returnUrl: string;

  constructor(
    private router: Router,
    private authService: AuthService,
    private alertService: AlertService) { }

  ngOnInit() {

  }
  login() {
    this.loading = true;
    this.authService.login(this.model.username, this.model.password)
        .subscribe(result => {
            console.log(result);
            if (result==true) {
                this.loading = false;
                //this.router.navigate(['/']);
                this.alertService.success('Success', true);
            } else {
                this.error = 'Username or password is incorrect';
                this.loading = false;
            }
        });
  }
}

你会发现一个错误

服务

return this.http.post<any>('http://localhost:3000/api/v1/users/login', {username:username, password:password})
          .map((res) => {
            console.log(res);
            let token = res.id ;
            let id = res.userId ;
            // login successful if there's a jwt token in the response
            if (token) {
              this.token = token;
                // store username and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token, id:id }));
                // return true to indicate successful login
                return true;
            } else {
                // return false to indicate failed login
                return false;
            }
        }).catch((error: Response) => {
        return Observable.throw(error.json());
    });

零件

   login() {
        this.loading = true;
        this.authService.login(this.model.username, this.model.password)
            .subscribe(result => {
                console.log(result);
                if (result==true) {
                    this.loading = false;
                    //this.router.navigate(['/']);
                    this.alertService.success('Success', true);
                } else {
                    this.error = 'Username or password is incorrect';
                    this.loading = false;
                }
            },(error)=>{
                   this.error = error.message?error.message:'Username or password is incorrect';
                    this.loading = false;
      }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM