I am encountering an issue with HttpClient. Every time I attempt to send a POST request from my frontend, I consistently receive a 401 Unauthorized error without even reaching the endpoint. I attempted using incognito mode to rule out any potential cache-related problems, but it seems that is not the root cause as the 401 error persists without contacting the endpoint. Interestingly, when testing with Postman, the request works flawlessly.
Below is my login service implementation:
@Injectable()
export class LoginService {
constructor(private http: HttpClient) {}
private handleError(error: HttpErrorResponse) {
if (error.status === 0) {
// Handle client-side or network errors accordingly.
console.error('An error occurred:', error.error);
} else {
console.log(error);
if (error.status === 401) {
return throwError(() => new Error('Email or password incorrect'));
}
// Handle backend unsuccessful response code and provide clues for debugging.
console.error(
`Backend returned code ${error.status}, body was: `,
error.error
);
}
// Return observable with user-facing error message.
return throwError(() => new Error('Try again in another moment'));
}
login(userData: UserData): Observable<UserData> {
return this.http
.post<UserData>(
`http://localhost:8000/api/auth/login`,
{ userData },
{ withCredentials: true }
)
.pipe(catchError(this.handleError));
}
}
Configuration details of the Angular app:
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(withFetch()),
importProvidersFrom(HttpClientModule),
provideClientHydration(),
],
};
The expected behavior is to receive a status code of 200 upon successful email and password validation.