Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
219 lines (178 loc) · 6.94 KB
/
Copy pathserver.js
File metadata and controls
219 lines (178 loc) · 6.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
// Require necessary packages
const express = require("express");
const path = require("path");
require("dotenv").config();
const mysql = require("mysql2/promise"); // Using promise-based MySQL
const cors = require("cors"); // CORS middleware
const jwt = require("jsonwebtoken"); // JWT for token generation
const multer = require("multer"); // File upload middleware
const fs = require("fs");
const axios = require("axios");
const FormData = require("form-data");
// Initialize the Express app
const app = express();
// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true })); // Ensure URL-encoded data is parsed
app.use(cors()); // Enable CORS to handle requests from different origins
app.use(express.static(path.join(__dirname, "templates")));
// Ensure uploads directory exists
const uploadDir = path.join(__dirname, "uploads");
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
// Database Connection (Using Promises for better async handling)
const db = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
});
// Route for the homepage (serve index.html by default)
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "templates", "index.html"));
});
// User Registration Route (Sign-up)
app.post("/registration", async (req, res) => {
console.log("Received request body:", req.body); // Debugging line
const { name, email, reg_no, password } = req.body;
// Validate the fields
if (!name || !reg_no || !email || !password) {
console.log("Missing fields!");
return res.redirect("/index.html?error=missing_fields");
}
try {
// Store user in the database
const query = `INSERT INTO doc_auth (name, email, reg_no, password) VALUES (?, ?, ?, ?)`;
await db.query(query, [name, email, reg_no, password]);
console.log("User registered successfully");
res.redirect("/index.html?success=registered");
} catch (err) {
console.error("Database Error:", err);
res.redirect("/index.html?error=database_error");
}
});
// User Login Route (Sign-in)
app.post("/login", async (req, res) => {
console.log("Received login request:", req.body);
const { email, password } = req.body;
// Validate input fields
if (!email || !password) {
console.log("Missing email or password!");
return res.redirect("/index.html?error=missing_credentials");
}
try {
// Step 1: Check if the email exists
const query = `SELECT * FROM doc_auth WHERE email = ?`;
const [results] = await db.query(query, [email]);
if (results.length === 0) {
console.log("Invalid login attempt: Email not found");
return res.redirect("/index.html?error=invalid_login");
}
// Step 2: User exists, now check password
const user = results[0];
const storedPassword = user.password;
const userName = user.name;
if (storedPassword !== password) {
console.log("Invalid login attempt: Incorrect password");
return res.redirect("/index.html?error=invalid_login");
}
// Step 3: Successful login
console.log("User Logged In:", userName);
res.redirect(`/dashboard.html?user=${encodeURIComponent(userName)}`);
} catch (err) {
console.error("Login Error:", err);
res.redirect("/index.html?error=login_failed");
}
});
// Multer Configuration for File Uploads
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads/"); // Ensure this directory exists
},
filename: function (req, file, cb) {
cb(null, Date.now() + "_" + path.basename(file.originalname)); // Prevent overwriting
},
});
const upload = multer({ storage: storage });
// Define Flask API URL
const FLASK_API_URL = "http://127.0.0.1:5000/predict";
// Route to handle image upload and call Flask API
app.post("/predict", upload.single("image"), async (req, res) => {
if (!req.file) {
return res.status(400).json({ error: "No image uploaded" });
}
try {
// Prepare FormData for Flask API
const formData = new FormData();
formData.append("file", fs.createReadStream(req.file.path));
// Call Flask API
const response = await axios.post(FLASK_API_URL, formData, {
headers: { ...formData.getHeaders() },
});
// Send Flask API response back to client
res.json(response.data);
} catch (error) {
console.error("Error calling Flask API:", error.message);
res.status(500).json({ error: "Internal Server Error", details: error.message });
} finally {
// Delete uploaded file after processing
fs.unlinkSync(req.file.path);
}
});
// API Endpoint to Add a Patient
app.post("/add-patient", (req, res) => {
try {
// Extract data from request body
const { doctorId, patientName, patientAge, patientGender, patientHistory, patientContact } = req.body;
// Validate input (Basic checks)
if (!doctorId || !patientName || !patientAge || !patientGender || !patientHistory || !patientContact) {
return res.status(400).json({ error: "All fields are required" });
}
// SQL Query to Insert Data
const query = `INSERT INTO patient_details (doctor_id, patient_name, age, gender, tumor_history, contact, created_at)
VALUES (?, ?, ?, ?, ?, ?, NOW())`;
// Execute Query
db.query(query, [doctorId, patientName, patientAge, patientGender, patientHistory, patientContact], (err, result) => {
if (err) {
console.error("Database error:", err);
return res.status(500).json({ error: "Database error", details: err.sqlMessage });
}
res.status(201).json({ message: "Patient added successfully!", patientId: result.insertId });
});
} catch (error) {
console.error("Unexpected server error:", error);
res.status(500).json({ error: "Internal Server Error" });
}
});
app.get("/search-patient", async (req, res) => {
let searchQuery = req.query.q ? req.query.q.trim() : null; // Trim input
if (!searchQuery) {
return res.status(400).json({ error: "Missing search query." });
}
try {
let sql, params;
// If the input is a number, search by ID
if (!isNaN(searchQuery)) {
sql = `SELECT * FROM patient_details WHERE id = ?`;
params = [searchQuery];
} else {
// Otherwise, search by patient name (case-insensitive)
sql = `SELECT * FROM patient_details WHERE LOWER(patient_name) LIKE LOWER(?)`;
params = [`%${searchQuery}%`];
}
const [results] = await db.query(sql, params);
if (results.length === 0) {
return res.status(404).json({ message: "No patient found." });
}
res.json(results);
} catch (err) {
console.error("Database error:", err);
res.status(500).json({ error: "Database query failed." });
}
});
// Start server
const PORT = process.env.PORT || 5055;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});