index.js
const express = require('express')
const mysql = require('mysql')
const path = require('path')
const dotenv = require('dotenv')
const bodyParser = require('body-parser')
const ejs = require('ejs')
const app = express()
dotenv.config() // Load environment variables from .env file
app.use(express.static(path.join(__dirname, 'public')))
app.use(bodyParser.json({ limit: '50mb' }))
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }))
// Set EJS as the view engine
app.set('view engine', 'ejs')
const connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
})
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL:', err)
return
}
console.log('Connected to MySQL!')
const createTableQuery = `
CREATE TABLE IF NOT EXISTS doctors (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
doctor_id VARCHAR(50),
hospital VARCHAR(255),
hospital_address VARCHAR(255),
specialist VARCHAR(255),
experience VARCHAR(255),
phone VARCHAR(20),
email VARCHAR(255),
password VARCHAR(255)
)
`
connection.query(createTableQuery, (err) => {
if (err) {
console.error('Error creating doctors table:', err)
} else {
console.log('Doctors table created or already exists')
}
})
})
app.get('/doctor', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'html', 'doctor_portal.html'))
})
app.post('/doctor/sign-up', async (req, res) => {
console.log('Received Form Data:', req.body)
try {
const {
doctor_name,
doctor_id,
hospital,
hospital_address,
specialist,
experience,
phone,
email,
password,
} = req.body
const insertQuery = `
INSERT INTO doctors (name, doctor_id, hospital, hospital_address, specialist, experience, phone, email, password)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`
await connection.query(insertQuery, [
doctor_name,
doctor_id,
hospital,
hospital_address,
specialist,
experience,
phone,
email,
password,
])
console.log('User signed up successfully')
res.redirect(`/doctor/${encodeURIComponent(doctor_name)}`)
} catch (error) {
console.error('Error signing up:', error)
res.status(500).send('Error signing up')
}
})
app.get('/doctor/:doctor_name', (req, res) => {
const doctorName = req.params.doctor_name
const getDoctorQuery = `
SELECT specialist, hospital, hospital_address, email FROM doctors WHERE name = ?
`
connection.query(getDoctorQuery, [doctorName], (err, results) => {
if (err) {
console.error('Error fetching doctor details:', err)
res.status(500).send('Error fetching doctor details')
} else {
const doctorDetails = results[0] // Assuming the doctor's name is unique
if (doctorDetails) {
// Extract details from doctorDetails
const specialist = doctorDetails.specialist
const hospital = doctorDetails.hospital
const location = doctorDetails.hospital_address // Use hospital_address here
const contactEmail = doctorDetails.email
// Fetch research items and degree items from the database if needed
const researchItems = [
'Advances in Heart Disease Treatment - Journal of Cardiology, 2022',
'Innovations in Cardiovascular Surgery - Journal of Medical Science, 2021',
]
const degreeItems = [
'MD in Cardiology - Medical University, 2010',
'Board Certified Cardiologist - American Board of Cardiology, 2012',
]
// Render the template with the data
res.render('doctor_profile', {
doctorName,
specialist,
hospital,
location,
contactEmail,
researchItems,
degreeItems,
})
} else {
console.log('Doctor not found:', doctorName)
res.status(404).send('Doctor not found')
}
}
})
})
const PORT = process.env.PORT || 4000
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`)
})
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something went wrong!')
})
doctor_portal.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Doctor Portal</title>
<link rel="stylesheet" href="../css/doctor_portal.css" />
</head>
<body>
<div class="container">
<div class="background-shapes"></div>
<form id="login-form">
<h2>Login</h2>
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username" required />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" required />
</div>
<div class="form-group" style="text-align: left;">
<a href="#" id="forgot-password">Forgot Password?</a>
</div>
<button type="submit">Login</button>
<div class="toggle-form" id="toggle-signup">
Don't have an account? Sign Up
</div>
</form>
<form
id="signup-form"
style="display: none;"
action="/doctor/sign-up"
method="POST"
>
<h2>Sign Up/Register</h2>
<div class="form-group">
<label for="doctor-name">Name</label>
<input type="text" id="doctor-name" name="doctor_name" required />
</div>
<div class="form-group">
<label for="doctor-id">ID</label>
<input type="text" id="doctor-id" name="doctor_id" required />
</div>
<div class="form-group">
<label for="hospital">Hospital</label>
<input type="text" id="hospital" name="hospital" required />
</div>
<div class="form-group">
<label for="hospital">Hospital Address</label>
<input
type="text"
id="hospital_address"
name="hospital_address"
required
/>
</div>
<div class="form-group">
<label for="hospital">Specialist in</label>
<input type="text" id="specialist" name="specialist" required />
</div>
<div class="form-group">
<label for="hospital">Experience</label>
<input type="text" id="experience" name="experience" required />
</div>
<div class="form-group">
<label for="phone">Phone Number</label>
<input type="tel" id="phone" name="phone" required />
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="email" required />
</div>
<div class="form-group">
<label for="password">Password</label>
<input
type="password"
id="password_signup"
name="password"
required
/>
</div>
<div class="form-group">
<label for="confirm-password">Confirm Password</label>
<input
type="password"
id="confirm-password"
name="confirm_password"
required
/>
</div>
<button type="submit" id="signup-button">Sign Up</button>
<div class="toggle-form" id="toggle-login">
Already have an account? Login
</div>
</form>
<form id="forgot-password-form" style="display: none;">
<h2>Forgot Password</h2>
<div class="form-group">
<label for="email-forgot">Email</label>
<input type="email" id="email-forgot" name="email-forgot" required />
</div>
<button type="submit">Reset Password</button>
<div class="toggle-form" id="toggle-login-forgot">
Remembered your password? Login
</div>
</form>
</div>
<script>
const loginForm = document.getElementById('login-form')
const signupForm = document.getElementById('signup-form')
const forgotPasswordForm = document.getElementById('forgot-password-form')
const toggleSignup = document.getElementById('toggle-signup')
const toggleLogin = document.getElementById('toggle-login')
const toggleLoginForgot = document.getElementById('toggle-login-forgot')
const forgotPasswordLink = document.getElementById('forgot-password')
toggleSignup.addEventListener('click', () => {
loginForm.style.display = 'none'
forgotPasswordForm.style.display = 'none'
signupForm.style.display = 'block'
})
toggleLogin.addEventListener('click', () => {
loginForm.style.display = 'block'
forgotPasswordForm.style.display = 'none'
signupForm.style.display = 'none'
})
toggleLoginForgot.addEventListener('click', () => {
loginForm.style.display = 'block'
forgotPasswordForm.style.display = 'none'
})
forgotPasswordLink.addEventListener('click', () => {
loginForm.style.display = 'none'
signupForm.style.display = 'none'
forgotPasswordForm.style.display = 'block'
})
forgotPasswordForm.addEventListener('submit', (event) => {
event.preventDefault()
})
signupForm.addEventListener('submit', async (event) => {
event.preventDefault()
const form = event.target
const formData = new FormData(form)
try {
const response = await fetch('/doctor/sign-up', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams(formData), // Convert FormData to URL-encoded format
})
if (response.ok) {
const data = await response.text()
if (data === 'User signed up successfully') {
console.log('Before redirection code')
const doctorName = formData.get('doctor_name')
alert('Doctor signup successful!')
}
} else {
console.error('Error:', response.statusText)
}
} catch (error) {
console.error('Error:', error)
}
})
</script>
</body>
</html>
doctor_profile.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Doctor Profile</title>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
/>
<link rel="stylesheet" href="../css/doctor_profile.css" />
</head>
<body>
<div id="navbar-container"></div>
<div class="profcontainer">
<div class="profile-card">
<div class="profile-image">
<label for="profile-upload" class="profile-image-upload">
<input
type="file"
id="profile-upload"
accept="image/*"
onchange="handleImageUpload(event)"
/>
<img
id="profile-image"
src="../assets/profile.png"
alt="Doctor Profile"
/>
</label>
</div>
<div class="profile-details">
<div class="profile-name">
<%= doctorName %>
</div>
<div class="profile-info">Specialist: <%= specialist %></div>
<div class="profile-info">Hospital: <%= hospital %></div>
<div class="profile-info">Location: <%= location %></div>
<div class="profile-info">Contact: <%= contactEmail %></div>
<button class="profile-button">Edit Profile</button>
</div>
<div class="research-section">
<div class="research-title">Researches and Publications</div>
<% researchItems.forEach((item) => { %>
<div class="research-item">
<%= item %>
</div>
<% }); %>
</div>
<div class="degree-section">
<div class="degree-title">Degrees and Certifications</div>
<% degreeItems.forEach((item) => { %>
<div class="degree-item">
<%= item %>
</div>
<% }); %>
</div>
</div>
</body>
<script>
const navbarContainer = document.getElementById('navbar-container')
fetch('./doctor_navbar.html')
.then((response) => response.text())
.then((content) => {
navbarContainer.innerHTML = content
})
const profileImage = document.getElementById('profile-image')
function handleImageUpload(event) {
const file = event.target.files[0]
if (file) {
const reader = new FileReader()
reader.onload = function (e) {
profileImage.src = e.target.result
}
reader.readAsDataURL(file)
}
}
</script>
</html>
** 描述:
提交表单后,我在 Express.js 中遇到了 res.redirect 函数的问题。我一直在开发一个网络应用程序,医生可以在其中注册并访问他们的个人资料。注册过程涉及表单提交和数据库插入。
成功注册新医生后,我尝试使用 res.redirect 将他们重定向到他们的个人资料页面。然而,尽管我做出了努力,重定向并未按预期工作。我尝试了 res.redirect 函数的不同变体,但表单提交后页面没有改变。
我尝试过的:
I've placed console.log statements before and after the res.redirect line to ensure that the code execution is reaching that point.
I've checked my server-side route to the doctor's profile page (/doctor/:doctor_name) and confirmed that it's correctly set up to render the profile template.
I've temporarily removed other middleware and code that might be interfering with the redirection process.
I've verified that the client-side JavaScript is handling the form submission and response correctly.
尽管做出了这些努力,我仍然无法使重定向正常工作。我希望收到有关如何排查和解决此问题的指导。 **
我认为问题在于,在更具体的路线之前,您有更通用的路线。
app.get('/doctor', (req, res) => {[...]})
应该在之后
app.get('/doctor/:doctor_name', (req, res) => {[...]})
顺序在 Express.js 中很重要