e_comm_chatbot_UI / server.js
aag111's picture
Update server.js
b320a3d verified
Raw History Blame Contribute Delete
2.37 kB
import express from "express";
import path from "path";
import { fileURLToPath } from "url";
import fetch from "node-fetch"; // For making backend API calls
// --------------------
// Setup paths
// --------------------
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
// --------------------
// Middleware setup
// --------------------
app.use(express.json());
app.use(express.static(path.join(__dirname, "public"))); // Optional frontend assets (HTML/CSS/JS)
// --------------------
// Config
// --------------------
const PORT = process.env.PORT || 7860;
// Replace with your Hugging Face Space API endpoint
const HF_API_URL = "https://aag111-fianl-chatbot.hf.space/chat";
// --------------------
// Chat endpoint
// --------------------
app.post("/chat", async (req, res) => {
try {
const userMessage = req.body.message;
if (!userMessage) {
return res.status(400).json({ reply: "Please send a valid message." });
}
// 🔹 Send the user's query to your FastAPI backend
const response = await fetch(HF_API_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
query: userMessage,
k: 3, // Retrieve top 3 similar answers from dataset
}),
});
if (!response.ok) {
const text = await response.text();
console.error("Backend error:", text);
return res.status(500).json({ reply: "Backend returned an error." });
}
const data = await response.json();
const botReply = data.answer || "Sorry, I couldn’t find a good answer.";
// Return the bot's response to the frontend
res.json({ reply: botReply });
} catch (error) {
console.error("❌ Error connecting to chatbot API:", error);
res.status(500).json({ reply: "Error connecting to chatbot API." });
}
});
// --------------------
// Root endpoint
// --------------------
app.get("/", (req, res) => {
res.send(`
<h1>🧠 Customer Support Chatbot</h1>
<p>Backend connected successfully. Use POST /chat to talk to the bot.</p>
`);
});
// --------------------
// Start the server
// --------------------
app.listen(PORT, () => {
console.log(`🚀 Chat frontend proxy running on port ${PORT}`);
console.log(`➡️ Connected to backend at: ${HF_API_URL}`);
});