From d65efc56ab00ec5719e0bd6896a7c1f8f264338d Mon Sep 17 00:00:00 2001 From: IO420 Date: Wed, 1 Oct 2025 15:57:38 -0600 Subject: [PATCH] added interceptors.response --- app/Components/auth/Login/Login.tsx | 2 +- app/lib/apiClient.ts | 49 ++++++++++++++++++++++++----- 2 files changed, 43 insertions(+), 8 deletions(-) diff --git a/app/Components/auth/Login/Login.tsx b/app/Components/auth/Login/Login.tsx index 0e8fae2..4cd7228 100644 --- a/app/Components/auth/Login/Login.tsx +++ b/app/Components/auth/Login/Login.tsx @@ -35,7 +35,7 @@ function Login() { const usuario = payload.usuario; document.cookie = `token=${token}; path=/; SameSite=Strict`; - document.cookie = `usuario=${usuario}; path=/; SameSite=Strict`; + document.cookie = `user=${usuario}; path=/; SameSite=Strict`; toast.success("Inicio de sesión exitoso"); router.push("/Impresiones"); diff --git a/app/lib/apiClient.ts b/app/lib/apiClient.ts index 0ffd831..4d321e6 100644 --- a/app/lib/apiClient.ts +++ b/app/lib/apiClient.ts @@ -2,22 +2,57 @@ import axios from "axios"; import Cookies from "js-cookie"; import { envConfig } from "./config"; +if (!envConfig.apiUrl) { + throw new Error("API URL is not defined in envConfig"); +} + const apiClient = axios.create({ baseURL: envConfig.apiUrl, + timeout: 10000, headers: { "Content-Type": "application/json", }, }); -apiClient.interceptors.request.use((config) => { - const token = Cookies.get("token"); - if (token) { - if (config.headers && "set" in config.headers) { - config.headers.set("Authorization", `Bearer ${token}`); +apiClient.interceptors.request.use( + (config) => { + const token = Cookies.get("token"); + if (token) { + config.headers.Authorization = `Bearer ${token}`; } + return config; + }, + (error) => { + return Promise.reject(error); } - return config; -}); +); + +apiClient.interceptors.response.use( + (response) => response, + (error) => { + if (error.response) { + const status = error.response.status; + + if (status === 401) { + Cookies.remove("token"); + Cookies.remove("user"); + + if ( + typeof window !== "undefined" && + !window.location.pathname.includes("/") + ) { + window.location.href = "/"; + } + } + + if (status === 403) { + window.location.href = "/Impresiones"; + } + } + return Promise.reject(error); + } +); export default apiClient; //IO +//Mike