Reputation: 912
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...
Upvotes: 0
Views: 874
Reputation: 431
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!
Upvotes: 1