EJS循环跳转仅传首个元素:为何无法获取其他索引数据?
Let's figure out why you're only pulling up the first movie's details no matter which list item you click—there are a couple of critical mistakes in your code causing this behavior:
1. Wrong URL Format in home.ejs
Your link includes an extra colon (:) in the href attribute. The :name in your Express route is just a placeholder, but your actual URL shouldn't include that colon. Right now, you're sending a parameter like :Inception instead of just Inception, which means Express can't correctly map it to your name route parameter.
Fixed home.ejs code:
<% data.forEach((item) => { %> <li> <a href="watch_movie/<%= encodeURIComponent(item.Name) %>"> <img src="<%= item.Image_path %>" height="200px" width="150px" alt="<%= item.Name %>"> </a> <p><%= item.Name %></p> </li> <% }); %>
I added encodeURIComponent here to handle movie names with spaces or special characters (like "The Matrix Reloaded")—these would break your URL if left unencoded.
2. Broken SQL Query in app.js
Your SQL query is comparing Name to the string literal name instead of the actual name variable from your route parameter. This means the query isn't filtering by the movie you clicked—it's either returning the first result in your table (if the query doesn't throw an error) or failing silently.
Fixed app.js route code:
app.get('/watch_movie/:name', (req, res) => { const name = decodeURIComponent(req.params.name); // Reverse the encoding from home.ejs const sql = "select * from Movies where Name = ?"; // Use a placeholder for safe parameter passing db.query(sql, [name], (err, result) => { // Pass the variable as a query parameter if (err) throw err; else { // No need to stringify/parse the result—db.query returns a JS object array directly if (result.length === 0) { return res.send("Sorry, that movie wasn't found!"); } const movie = result[0]; console.log(movie); res.render('watch_movie', { path: movie }); } }); });
Key improvements here:
- Removed unnecessary
JSON.stringify/JSON.parse—the database result is already a usable JavaScript object. - Used a parameterized query (
?placeholder) to avoid SQL injection and correctly pass the movie name variable. - Added a check for empty results (in case someone enters a movie name that doesn't exist in your database).
- Used
decodeURIComponentto reverse the URL encoding we did inhome.ejs.
3. Quick Check for watch_movie.ejs
Your current watch_movie.ejs code looks fine, but just make sure path.Video_path matches the exact column name from your database (case-sensitive in some SQL setups). If your column is named video_path instead of Video_path, that could cause issues too.
After fixing these issues, each list item will pass the correct movie name to your route, and your SQL query will fetch the matching movie data instead of always returning the first entry.
内容的提问来源于stack exchange,提问作者user8614580

