Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

Angular Laravel authentication bad request

I have build a laravel rest Api and I want to use it my angular project. I have build a form for login user but when i submit the formular i get this error POST http://localhost:8000/oauth/token 400 (Bad Request) I don't know how to solve it. here is my authService.ts file

export class AuthService {

  //variables 
  authUrl = 'http://localhost:8000/oauth/token';
  apiUrl =  'http://localhost:8000/api';
  options: any;
  constructor(private http: HttpClient) {
      this.options = {
        headers: new HttpHeaders({
          Accept: 'application/json',
          'Content-Type': 'application/json'
        })
      };
    }

     
    login(e :string, p: string) {
      return this.http.post(this.authUrl, {
        grant_type: 'password',
        client_id: '2',
        client_secret: '9oi905dZlXpGTGdTjB7Yciqs3XpFEHGiqzTqbkU6',
        username: e,
        password: p,
        scope: '*'
      }, this.options);
    }

    /**
     * Revoke the authenticated user token
     */

    logout(){
      this.options.headers.Authorization = 'Bearer ' + localStorage.getItem('access_token');
      return this.http.get(this.apiUrl + '/token/revoke', this.options);
    }

}

and here is the signin.component.ts

export class SigninComponent implements OnInit {

  signInForm: FormGroup; 
  loading: boolean;
  errors: boolean;

  constructor(private formBuilder: FormBuilder,
              private authService: AuthService,
              private router: Router) { }

  ngOnInit(): void {
    this.initForm();
  }

  initForm() {
    this.signInForm = this.formBuilder.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, Validators.pattern(/[0-9a-zA-Z]{4,}/)]]
    })
  }

  onSubmit() {
    this.loading = true;
    this.errors = false;
    const email = this.signInForm.get('email').value;
    const password = this.signInForm.get('password').value;
    this.authService.login(email, password).subscribe(
      (res: any) => {
        localStorage.setItem('acces_token', res.acces_token);
        this.loading = false;
        console.log("success");
        //navigate to the home page
        this.router.navigate['/books']; 
      }, (err: any) => {
        this.loading = false;
        this.errors = true;
        console.log("Merde combi !");
      }
    );
  }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...