Node.js中点击EJS页面Div,如何在plugDashboard获取MAC地址并打印日志?
Got it, let's get this working for you. The root problem here is that your current /plugDashboard link doesn't carry any information about the clicked device—so the server has no way to know which one was selected. Here's how to fix it step by step:
1. Update the EJS Link to Include the Device MAC Address
Modify the <a> tag in your EJS template to pass the device_address as a URL query parameter. This will send the MAC address along with the navigation request:
<a href="/plugDashboard?deviceAddr=<%= data.result[i].device_address %>"> <p><img class="img-fluid" src="/images/plugimg.png" alt="Plug Image"></p> <p><h3><%= data.result[i].device_name %></h3></p> <p><h6><%= data.result[i].device_address %></h6></p> </a>
The <%= %> syntax safely escapes the value to prevent XSS issues, so you don't have to worry about malicious input here.
2. Modify the /plugDashboard Route to Capture and Log the MAC Address
Now, update your server-side route to read the deviceAddr parameter from the request query string and print it to the logs:
app.get('/plugDashboard', checkAuthenticted, (req, res) => { // Extract the device MAC address from the query parameters const deviceMac = req.query.deviceAddr; console.log("Selected device MAC address:", deviceMac); res.render('plugDashboard'); })
Why This Works
When a user clicks a device div, the browser will navigate to a URL like /plugDashboard?deviceAddr=AA:BB:CC:DD:EE:FF. The server's req.query object will contain this deviceAddr key, letting you access the MAC address and log it immediately.
Bonus: Quick Security Note
While we're at it, your /usrDashboard route has a SQL injection risk because you're directly concatenating the email variable into the query. Consider using parameterized queries instead to harden your code:
con.query("SELECT device_name, device_address FROM pluglist WHERE email = ?", [email], (err, result, fields)=> { // ... rest of your existing code })
This is safer and prevents attackers from manipulating the query string to access unauthorized data.
内容的提问来源于stack exchange,提问作者Prithwi Chanda

