Frontend API Service
Relevant source files
The following files were used as context for generating this wiki page:
The Frontend API Service acts as the communication bridge between the React application and the backend server. It is responsible for handling HTTP requests, managing authentication tokens via LocalStorage, and providing structured services for interacting with user data, product listings, and authentication flows.
The service is implemented using both standard fetch API and the axios library, providing support for asynchronous operations and centralized error handling. It ensures that every outgoing request to protected resources includes the necessary JWT (JSON Web Token) within the authorization headers.
Architecture and Core Configuration
The API service is structured into modular objects (usuariosService, productosService, authService) that encapsulate related logic. The environment configuration defines the base URL for the backend, typically pointing to http://localhost:5230 or http://localhost:3000/api depending on the implementation version.
Sources: Front/src/services/api.js:1, Front/src/services/api.ts:31, Back/Alumnos/Api/Properties/launchSettings.json:13
Request Interception and Headers
To maintain secure sessions, the service implements an interception mechanism. For every request, it checks localStorage for a stored token. if present, it attaches a Bearer token to the Authorization header.
The logic ensures that the frontend remains synchronized with the backend's security requirements.
Sources: Front/src/services/api.js:15-18, Front/src/services/api.ts:38-44
Service Modules
Authentication Service (authService)
Handles the user lifecycle regarding sessions. It provides methods for logging in and clearing local session data.
| Method | Parameters | Description |
|---|---|---|
login | credenciales | Sends credentials to /login and receives session data. |
logout | None | Removes the 'token' from localStorage. |
Sources: Front/src/services/api.js:132-146, Front/src/services/api.ts:143-154
User Management Service (usuariosService)
Provides comprehensive CRUD operations for user profiles. It supports advanced features like partial updates and image uploads using FormData.
Product Management Service (productosService)
This module manages the catalog of items. It allows for searching, creating, and deleting products within the store.
| Endpoint | Method | Purpose |
|---|---|---|
/productos | GET | List products with filters (name, availability). |
/productos/{id} | GET | Retrieve details for a specific product. |
/productos | POST | Create a new product entry. |
/productos/{id} | DELETE | Remove a product from the system. |
Sources: Front/src/services/api.js:80-129, Front/src/services/api.ts:109-140
Implementation Details
Response Handling
A centralized handleResponse function is used to process results. It checks the Authorization header of the response; if the backend rotates or provides a new token, the service automatically updates the stored token in localStorage.
const handleResponse = async (response) => {
if (!response.ok) {
const error = await response.text();
throw new Error(error);
}
const token = response.headers.get('Authorization');
if (token) {
localStorage.setItem('token', token);
}
return response.json();
};
Sources: Front/src/services/api.js:4-13, Front/src/services/api.ts:47-56
Backend Integration (CORS and Auth)
The backend (C#/.NET) is configured to support these frontend services by exposing the Authorization header and defining CORS policies that allow requests from the React application origin.
builder.Services.AddCors(conf =>
{
conf.AddPolicy("PoliticasCors", options => options.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.WithExposedHeaders("Authorization"));
});
Sources: Back/Alumnos/Api/Program.cs:48-54
Summary
The Frontend API Service provides a robust abstraction layer for data fetching and state persistence. By centralizing authentication header management and response parsing, it allows UI components like Profile or ProductDetail to interact with the backend through simple, typed (in the case of TypeScript) function calls. The service effectively manages JWT-based security while providing standardized error handling across the application.