fix: dynamic backend address based on frontend address

This commit is contained in:
Stijnvandenbroek
2025-08-22 10:01:04 +02:00
parent 794e5d256f
commit f810c60f38
7 changed files with 73 additions and 5 deletions

View File

@@ -2,6 +2,7 @@ import React, { useState } from 'react';
import Home from './components/Home';
import Quiz from './components/Quiz';
import axios from 'axios';
import getApiUrl from './utils/apiConfig';
function App() {
const [sessionId, setSessionId] = useState('');
@@ -93,7 +94,8 @@ function App() {
const handleRetryQuiz = async () => {
try {
await axios.post('http://backend:8000/reset-session/', {
const apiUrl = getApiUrl();
await axios.post(`${apiUrl}/reset-session/`, {
session_id: sessionId,
});
setIsTransitioning(true);

View File

@@ -1,8 +1,9 @@
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import getApiUrl from '../utils/apiConfig';
const Home = ({ setSessionId, setQuizStarted }) => {
const API_URL = process.env.REACT_APP_API_URL || 'http://localhost:8000';
const API_URL = getApiUrl();
// File state
const [files, setFiles] = useState([]);
@@ -31,7 +32,9 @@ const Home = ({ setSessionId, setQuizStarted }) => {
formData.append('settings', JSON.stringify(quizSettings));
console.log('API URL:', API_URL);
console.log('Frontend URL:', window.location.href);
console.log('Frontend Host:', window.location.hostname);
console.log('Detected API URL:', API_URL);
console.log('Uploading files:', files.map(f => f.name));
console.log('Quiz settings:', quizSettings);

View File

@@ -1,8 +1,9 @@
import React, { useState, useEffect, useCallback } from 'react';
import axios from 'axios';
import getApiUrl from '../utils/apiConfig';
const Quiz = ({ sessionId, onGoHome, onRetry }) => {
const API_URL = process.env.REACT_APP_API_URL;
const API_URL = getApiUrl();
// Quiz state
const [questionData, setQuestionData] = useState(null);

View File

@@ -0,0 +1,18 @@
// Dynamically determine API URL based on how the frontend is accessed
const getApiUrl = () => {
if (process.env.REACT_APP_API_URL) {
return process.env.REACT_APP_API_URL;
}
const currentHost = window.location.hostname;
const apiPort = '8000';
if (currentHost === 'localhost' || currentHost === '127.0.0.1') {
return `http://localhost:${apiPort}`;
}
// Use same host for LAN/network access
return `http://${currentHost}:${apiPort}`;
};
export default getApiUrl;