EJS渲染POST数据时出现data is not defined错误,寻求技术帮助
Hey there! Let's break down how to fix that "data is not defined" error you're hitting when trying to pass POST data from /admin.ejs to /home.ejs. Since you suspect the issue is in adminRouter.js, we'll start there and work through all possible points of failure.
1. First: Check Your adminRouter.js POST Handler
The most likely culprit is that you're not passing the submitted data to the /home.ejs template when handling the POST request. Here's what a correct implementation might look like:
If you're directly rendering /home.ejs after the POST:
// adminRouter.js const express = require('express'); const router = express.Router(); router.post('/submit', (req, res) => { // Capture the POST data from the admin form const submittedData = req.body; // Pass the data explicitly to the home template res.render('home', { data: submittedData }); }); module.exports = router;
If you're redirecting to /home (instead of rendering directly), you'll need to store the data temporarily (like in a session) because redirects are GET requests that can't carry POST data:
// adminRouter.js router.post('/submit', (req, res) => { const submittedData = req.body; // Store data in session (make sure you have session middleware set up!) req.session.submittedData = submittedData; res.redirect('/home'); });
2. Fix the /home Route in indexRouter (If Using Redirects)
If you went the redirect route, your indexRouter needs to pull the data from the session and pass it to /home.ejs:
// indexRouter.js router.get('/home', (req, res) => { // Grab the data from session (fallback to null if none exists) const data = req.session.submittedData || null; // Pass it to the template res.render('home', { data: data }); // Optional: Clear the session data so it doesn't persist on refresh delete req.session.submittedData; });
3. Safeguard /home.ejs Against Missing Data
Even if you pass the data correctly, it's smart to add a check in your EJS template to avoid errors if no data exists:
<!-- home.ejs --> <h1>Home Page</h1> <% if (data) { %> <div class="submitted-data"> <h3>Submitted Admin Data:</h3> <p>Name: <%= data.name %></p> <p>Message: <%= data.message %></p> <!-- Adjust fields to match your form --> </div> <% } else { %> <p>No admin data submitted yet.</p> <% } %>
4. Double-Check Your Middleware Setup in index.js
Make sure you have the necessary middleware to parse POST data and handle sessions (if using them):
// index.js const express = require('express'); const bodyParser = require('body-parser'); const session = require('express-session'); const indexRouter = require('./routes/indexRouter'); const adminRouter = require('./routes/adminRouter'); const app = express(); // Parse form data (required to access req.body in POST routes) app.use(bodyParser.urlencoded({ extended: true })); // Session middleware (only needed if you're redirecting with data) app.use(session({ secret: 'your-own-secret-key-here', // Replace with a real secret resave: false, saveUninitialized: true })); // Mount your routers app.use('/', indexRouter); app.use('/admin', adminRouter); app.listen(3000, () => console.log('Server running on port 3000'));
The core issue here is almost certainly that the data variable isn't being passed to /home.ejs when it's rendered. By explicitly passing the data from your POST handler (or pulling it from the session if redirecting) and adding a safety check in the template, you should resolve that error.
内容的提问来源于stack exchange,提问作者Adrian Marica

