I’m facing a weird issue with my Angular app. When I use ngOnInit to fetch data, it sends two GET requests to my Node+Express backend. The first one comes without a token, and the second contains it. This problem doesn’t occur when using Postman since it only sends a single request.
Here is my Angular service method:
async fetchAllItems(): Promise<Item[]> {
try {
return await firstValueFrom(
this.http.get<Item[]>('http://api.example.com/items', {
withCredentials: true
})
);
} catch (error) {
console.error(error);
throw error;
}
}
And the backend middleware checking for auth tokens:
const checkAuth = (req, res, next) => {
// Authentication logic
next();
};
app.use(cors({ origin: 'http://localhost:4200', credentials: true }));
app.use(checkAuth);
In my component, the service is called like this:
async ngOnInit() {
try {
this.items = await this.itemService.fetchAllItems();
} catch (error) {
console.error('Failed to fetch items', error);
}
}
The error message only appears on Angular’s development server console, not in the browser console. I’ve experimented with various CORS configurations, but nothing seems to rectify the issue. Any help is appreciated.