Anpassat till den nya designen där Flask skapar websidor m.h.a. mallar. Webfiler (html, css, js) har flyttats till egna kataloger.

This commit is contained in:
2024-07-25 00:41:50 +02:00
parent f179e8e19b
commit ccc8e73f48
5 changed files with 42 additions and 11 deletions
+60
View File
@@ -0,0 +1,60 @@
// Get the user input element from the DOM
const chatbox = document.getElementById('chatbox');
const userInput = document.getElementById('userInput');
// Get API endpoint for chat from environment variable
const apiEndpoint = process.env.BE_API_ENDPOINT || 'http://localhost:5005/api/chat'; // Default if not found
console.log("The API Endpoint is:", apiEndpoint);
// Define a function to send the user's message to the AI
function sendMessage() {
// Get the user's input message and trim any whitespace
const query = userInput.value.trim();
// Check if the message is not empty
if (query !== '') {
// Send a POST request to the /api/chat endpoint with the message
// fetch('http://localhost:5005/api/chat', {
fetch(apiEndpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query }),
})
.then(response => response.json())
.then(data => {
// Get the AI's response from the API data
const aiResponse = data.response;
// Render the user's original message in the chatbox
renderMessage(query, 'user-message');
// Render the AI's response in the chatbox
renderMessage(aiResponse, 'ai-response');
// Clear the user input field for the next message
userInput.value = '';
})
.catch(error => console.error('Error sending message:', error));
}
}
// Define a function to render a message in the chatbox with a specific class name
function renderMessage(text, className) {
// Create a new div element to hold the message
const messageElement = document.createElement('div');
// Add the specified class name to the element
messageElement.className = className;
// Set the text content of the element to the message text
messageElement.textContent = text;
// Append the message element to the chatbox
chatbox.appendChild(messageElement);
}