From 0e71bc432fc869d9f8e1ce5524057914082a3b48 Mon Sep 17 00:00:00 2001 From: Baligh ZOGHLAMI Date: Tue, 9 Jul 2024 10:47:39 +0100 Subject: [PATCH] fix fetch request --- src/app/lib/fetchRequest.js | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/src/app/lib/fetchRequest.js b/src/app/lib/fetchRequest.js index 6ad19f1..bf513fe 100644 --- a/src/app/lib/fetchRequest.js +++ b/src/app/lib/fetchRequest.js @@ -1,32 +1,44 @@ import Cookies from 'js-cookie'; import { decrypt } from "@/app/lib/session"; -const BASE_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000" +const BASE_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000"; + const fetchRequest = async (url, options = {}) => { const jwtCookie = Cookies.get('session'); - console.log('jwtCookie', jwtCookie) + console.log('jwtCookie', jwtCookie); const jwtDecrypted = await decrypt(jwtCookie); - console.log('jwtDecrypted', jwtDecrypted?.sessionData?.token) + console.log('jwtDecrypted', jwtDecrypted?.sessionData?.token); + const headers = { ...options.headers, - // add authorization header with token if there is jwtDecrypted.sessionData.token + // Add authorization header with token if there is jwtDecrypted.sessionData.token Authorization: jwtDecrypted?.sessionData?.token ? `Token ${jwtDecrypted.sessionData.token}` : undefined, }; + // Check if the body is FormData + const isFormData = options.body instanceof FormData; + + // If the body is not FormData, set Content-Type to application/json + if (!isFormData) { + headers['Content-Type'] = 'application/json'; + } + const response = await fetch(`${BASE_URL}${url}`, { ...options, headers, }); - console.log(response.status) + + console.log(response.status); if (!response.ok) { try { const errorData = await response.json(); - return { isSuccess: false, errors: errorData, data: null, status: response.status } + return { isSuccess: false, errors: errorData, data: null, status: response.status }; } catch (error) { - return { isSuccess: false, errors: error, data: null, status: response.status } + return { isSuccess: false, errors: error, data: null, status: response.status }; } } - console.log('response', response) + + console.log('response', response); let data = null; // Check if the response has content before parsing it as JSON const contentType = response.headers.get('content-type'); @@ -38,4 +50,4 @@ const fetchRequest = async (url, options = {}) => { return { isSuccess: true, errors: null, data: data, status: response.status }; }; -export default fetchRequest; +export default fetchRequest; \ No newline at end of file -- GitLab