I am encountering an issue with Angular’s HttpClient where a GET request to my server returns different data compared to a jQuery AJAX request for the same endpoint. I am using Flask for my backend, with CORS: CORS(app, supports_credentials=True). It currently works for POST requests (for sign in and sign out).
Problem Description:
When I make a GET request to my Flask server using jQuery AJAX, everything works as expected, and I receive the correct user information. However, when I attempt the same GET request using Angular’s HttpClient, I receive a response indicating that the user is not authenticated ({“is_authenticated”: False}), even though the user is authenticated.
Here is the working jQuery AJAX code:
$(document).ready(function() {
fetchPlayerInfo();
});
function fetchPlayerInfo() {
$.ajax({
type: "GET",
url: "http://localhost:5000/api/player/info",
xhrFields: {
withCredentials: true
},
crossDomain: true,
success: function(response) {
console.log("Fetch player info successful:", response);
},
error: function(response) {
console.log("Fetch player info failed:", response);
}
});
}
And here is my Angular code that is not working as expected:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from "@angular/common/http";
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrl: './header.component.scss'
})
export class HeaderComponent implements OnInit {
private baseUrl = 'http://localhost:5000/api';
constructor(private http: HttpClient) {}
ngOnInit() {
const url = `${this.baseUrl}/player/info`;
this.http.get<any>(url, {withCredentials: true}).subscribe((data) => {
console.log('UserInfo:', data);
});
}
}
My backend is in Flask. Here is the relevant router endpoint:
@player_bp.route('/info', methods=['GET'])
def get_player_info():
print("Session: ", dict(session))
print("Current User: ", current_user)
if current_user.is_authenticated:
player_info = {"is_authenticated": True, "name": current_user.name}
else:
player_info = {"is_authenticated": False}
return jsonify(player_info)
Additional Observations:
- The issue only occurs when the Angular HttpClient request is made in the ngOnInit lifecycle hook.
- If I trigger the same HTTP request through an Angular event handler (e.g., by clicking a button), it works correctly, similar to the jQuery AJAX request.
- This behavior leads me to believe that the problem might be related to the timing of the HTTP request or the management of the authentication state during the component’s initialization.
Why is Angular’s HttpClient not returning the correct data when the request is made in the ngOnInit lifecycle hook? Should I just drop Angular?