I am trying to create a web app to retrieve records from a mysql database but it seems i keep getting the 404 not found error. I am suing node.js for server side, and it seems that my endpoints are matching, but I am still getting an error. Any suggestions? Running the server on port 3001 and testing the webapp using a liver server feature in vscode on port 3001. New to programming web apps, would be grategul if you could point to a tutorial on making web apps to interact with a mysql database. Below is the code for the search.js:
const searchButton = document.getElementById('search-button');
const searchBar = document.getElementById('search-bar');
const studentInfoDiv = document.getElementById('student_Info');
searchButton.addEventListener('click', async () => {
const studentId = searchBar.value;
if (!studentId) {
studentInfoDiv.innerHTML = 'Please enter a student ID to search';
return;
}
try {
const response = await fetch(`/search/${studentId}`); // Assuming server is on port 3000
if (!response.ok) {
throw new Error(`Error: ${response.status}`);
}
const studentInfo = await response.text();
studentInfoDiv.innerHTML = studentInfo;
} catch (error) {
console.error(error);
studentInfoDiv.innerHTML = 'Error retrieving student information';
}
});
And here is the part of server.js
app.get('/search/:studentId', async (req, res) => {
const studentId = req.params.studentId;
try {
const [rows] = await pool.query('SELECT * FROM 2223_reportcard WHERE st_id = ?', [studentId]);
if (rows.length > 0) {
const student = rows[0];
const student_Info = `<h2>Student Info</h2>
<p>ID: ${student.st_id}</p>
<p>Name: ${student.name}</p>
<p>Class: ${student.class}</p>
<p>Class No.: ${student.cla_num}</p>`;
res.send(student_Info);
} else {
res.status(404).send('Student not found');
}
} catch (error) {
console.error(error);
res.status(500).send('Server Error');
}
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
Trying to display the student record by typing the id in the search bar. And display the information.