Angular HttpErrorResponse 401 (не авторизовано) - PullRequest
0 голосов
/ 21 апреля 2020

Я создаю веб-приложение на Angular и Loopback, но при попытке входа из внешнего интерфейса оно выдает следующую ошибку:

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!");
      }
    });
   }
  }
}

Я подтвердил Запрос URL на Почтальоне, и он не выдал никакой ошибки. Я смотрел другие подобные посты, но я видел, что ошибка 401 может иметь различное происхождение

Как я могу решить эту ошибку?

...