Angular HttpErrorResponse 401(未经授权)

时间:2020-04-21 03:23:59

标签: node.js angular web-deployment loopbackjs unauthorized

我正在Angular和Loopback上制作一个Web应用程序,但是当尝试从前端登录时,它会引发以下错误:

POST http://localhost:3000/api/usuarios/login?include=User 401 (Unauthorized)

ERROR HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "Unauthorized", url: "http://localhost:3000/api/usuarios/login?include=User", ok: false, …}

显示详细的错误代码:

status: 401
statusText: "Unauthorized"
url: "http://localhost:3000/api/usuarios/login?include=User"
ok: false
name: "HttpErrorResponse"
message: "Http failure response for http://localhost:3000/api/usuarios/login?include=User: 401 Unauthorized"
error: {error: {…}}
__proto__: HttpResponseBase 

我认为无论是在安全模型上还是在login-component.ts上,我都没有错误的代码,但是无论如何,我还是希望对此代码进行审查。

security.service.ts

import { BehaviorSubject, Observable } from 'rxjs';
import { UsuarioModel } from '../models/usuario.model';
import { HttpClient, HttpHeaders } from '@angular/common/http';


@Injectable({
  providedIn: 'root'
})
export class SecurityService {

  name:string='';


  userLogged:boolean=false;

  url:String= "http://localhost:3000/api/usuarios/";
  infoUsuario= new BehaviorSubject<UsuarioModel>(new UsuarioModel());

  constructor(private http: HttpClient) { 
    this.verificarSesionUsuario();
  }

  loginUser(username:String,pass:String):Observable<UsuarioModel>
  {
       return this.http.post<UsuarioModel>(`${this.url}login?include=User`, {
       email:username,
       contraseña:pass
     },
     {
       headers: new HttpHeaders({
         "content-type":"application/json"
       })
     })
}

} 

login.component.ts

import {FormGroup, FormBuilder,Validators} from '@angular/forms';
import{Router}from'@angular/router';
import{SecurityService}from'src/app/services/security.service';


declare var openPlatformModalMessage: any

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']

})
export class LoginComponent implements OnInit {

  fgValidation:FormGroup;

  constructor(private fb:FormBuilder, private secService:SecurityService,

    private router:Router) { }

  ngOnInit() {
    this.fgValidationBuilder();
  }

  loginEvent(){
    if(this.fgValidation.invalid){
      alert("Datos erróneos");

    }
    else{
      let u =this.fg.username.value;
      let p=this.fg.password.value;

      this.secService.loginUser(u,p).subscribe(data=>{

        if (data != null){
          console.log(data)
          this.router.navigate(['/home']);
          this.secService.saveLoginInfo(data);
      }

      else
      {
        openPlatformModalMessage("Los datos no son válidos!");
      }
    });
   }
  }
}

我已经在Postman上验证了URL请求,但没有引发任何错误。 我看过其他类似的帖子,但看到401错误的起因可能不同

如何解决此错误?

0 个答案:

没有答案