Newer
Older
My-Portfolio / frontend / src / api.js
  1. // api.js
  2. const API_URL = import.meta.env.VITE_API_URL;
  3. // A helper function for making API requests
  4. export const fetchData = async (endpoint) => {
  5. try {
  6. const response = await fetch(`${API_URL}/${endpoint}`);
  7. // Check if the response is actually JSON
  8. const text = await response.text();
  9. if (!response.ok) {
  10. throw new Error(`Error: ${response.statusText}`);
  11. }
  12. // Try parsing as JSON
  13. const data = JSON.parse(text);
  14. return data;
  15. } catch (error) {
  16. console.error("API request failed:", error.message);
  17. throw error;
  18. }
  19. };
  20. // Send data to the server
  21. export const postData = async (endpoint, payload) => {
  22. try {
  23. const response = await fetch(`${API_URL}/${endpoint}`, {
  24. method: "POST",
  25. headers: { "Content-Type": "application/json" },
  26. body: JSON.stringify(payload),
  27. });
  28. const data = await response.json();
  29. if (!response.ok) {
  30. throw new Error(data.error || "Something went wrong");
  31. }
  32. return data;
  33. } catch (error) {
  34. console.error("API POST request failed:", error.message);
  35. throw error;
  36. }
  37. };