简体   繁体   中英

angular laravel unauthorized 401 error

Okay, I don't know what I am doing wrong, but I really tried everything. In agular I just send user data to sign up

signUp(userData: LoginData) {
    return this.http.post(`${this.rootPath}api/signup`, userData);
  }

On backend

public function login()
    {
        $credentials = request(['email', 'password']);

        if (! $token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'Email or password doesn\'t exist'],
                401);
        }

        return $this->respondWithToken($token);
    }

    public function signup(signUp $request)
    {
        User::create($request->all());
        return $this->login();
    }

signUp

public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required'
        ];
    }

It adds new user to database, but I ALWAYS get 401 error which says user is not authorized. It is strange and I can't unerstand what am I doing wrong... Field REMEMBER_TOKEN is null, but I think it is not the problem...

I'd like to add info in case it is useful for other people. I have fixed the issue that is related to this. I am working in Angular 7, and Laravel 5.7 as API REST. In angular I created an interceptor in order to add the headers 'automatically'. And then, I've created the API for private routes and also experienced these issues described above. POSTMAN and Advanced REST worked well, the problem were the requests by Angular. And now, I've added the headers manually in each HTTP request as follows;

//Example for 'GET' request

userLogOut(): Observable<any[]> {
    let parameters = new HttpHeaders();
    parameters = parameters.set('Authorization', "Bearer " + this.session.getToken());
    return this.http.get<any[]>(this.usersUrl + 'logout', { headers: parameters });
}

//Example for 'POST' request

userLogOut(): Observable<any[]> {
    let parameters = new HttpHeaders();
    parameters = parameters.set('Authorization', "Bearer " + this.session.getToken() );
    return this.http.post<any[]>(this.usersUrl + 'logout', '', { headers: parameters } );
}

Both of them work well. Don't forget to add this at your constructor

private http: HttpClient 

and

import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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