Sails.js 1.0中req.session.flash清空失效问题求助
Hey there! I’ve dealt with this exact flash message issue in Sails 1.0 before, so let’s break down what’s going on and how to fix it.
The core problem here is that your flash messages aren’t being cleared at the right moment. When you set req.session.flash = {} in your POST registration handler, it doesn’t actually clear the message for the subsequent GET request that renders the form (since the redirect creates a new request cycle). Here’s how to fix it properly:
Step 1: Split Your Registration Flow into Two Controller Actions
You need separate handlers for displaying the registration form (GET request) and processing the form submission (POST request). This lets you clear the flash message when the form is loaded, not when submission fails.
Step 2: Update Your UsersController.js
Here’s a revised version of your controller with the correct flash handling:
module.exports = { // Show the registration form showRegister: function(req, res) { // Extract any flash messages and immediately clear the session const flashMessages = req.session.flash || {}; req.session.flash = {}; // Pass messages to the view for display return res.view('register', { flash: flashMessages }); }, // Process registration form submission processRegister: async function(req, res) { try { // Run your validation logic here const { email, password } = req.body; let validationErrors = []; if (!email) validationErrors.push('Email is required'); if (!password || password.length < 6) validationErrors.push('Password must be at least 6 characters'); // If validation fails, store errors in flash and redirect back to form if (validationErrors.length > 0) { req.session.flash = { error: validationErrors.join(' ') }; return res.redirect('/register'); } // If validation passes, create the user (example logic) await User.create({ email, password: await sails.helpers.passwords.hashPassword(password) }); // Optional: Set success message for login page req.session.flash = { success: 'Registration complete! Please log in.' }; return res.redirect('/login'); } catch (err) { req.session.flash = { error: err.message }; return res.redirect('/register'); } } };
Step 3: Configure Your Routes Correctly
Make sure your routes map to the right actions in config/routes.js:
module.exports.routes = { 'GET /register': 'UsersController.showRegister', 'POST /register': 'UsersController.processRegister', // Other routes... };
Step 4: Update Your View to Use Passed Flash Messages
In your registration view (e.g., views/register.ejs), use the flash variable passed from the controller instead of directly accessing req.session.flash:
<!-- Display error messages if they exist --> <% if (flash.error) { %> <div class="alert alert-danger"><%= flash.error %></div> <% } %> <!-- Display success messages if they exist --> <% if (flash.success) { %> <div class="alert alert-success"><%= flash.success %></div> <% } %> <!-- Registration form --> <form action="/register" method="POST"> <div> <label>Email:</label> <input type="email" name="email" value="<%= req.body.email || '' %>"> </div> <div> <label>Password:</label> <input type="password" name="password"> </div> <button type="submit">Register</button> </form>
Why This Works
- When validation fails, we store errors in
req.session.flashand redirect to the GET/registerroute. - The
showRegisteraction grabs the flash messages, clears the session immediately, then passes the messages to the view. - When the user refreshes the page, the GET request runs again—but
req.session.flashis already empty, so no old messages show up.
内容的提问来源于stack exchange,提问作者user9102933

