如何在Node.js与Pug模板HTML间实现POST传值并同页回显结果
Got it, let's walk through how to make this work—submitting your Pug form via POST to the /form route, processing the input on the Node.js side, and showing the result right on the same page. I'll cover two common approaches: a traditional page-refresh method, and an asynchronous (no-refresh) method.
1. Traditional Page-Refresh Approach
This is the simplest setup, where submitting the form refreshes the page but preserves your input and displays the processed result.
Step 1: Update Your Pug Template
Modify your form to include a readonly textarea for the result, and pass variables to retain user input and show the processed value:
form(action='/form' method='post') p.lead // Preserve the user's input when the page reloads textarea(style='resize:none; width:400px; height:300px;' name='description' onkeydown="if(event.keyCode===9) { event.preventDefault(); this.value += ' '; }")= description || '' p button(type='submit') Process Input p.lead // Readonly textarea for the processed result textarea(style='resize:none; width:400px; height:300px;' name='result' readonly)= processedResult || ''
Step 2: Node.js (Express) Route Setup
First, install the required dependencies:
npm install express pug body-parser
Then set up your routes to handle loading the form and processing the input:
const express = require('express'); const bodyParser = require('body-parser'); const app = express(); // Configure Pug as the template engine app.set('view engine', 'pug'); // Parse URL-encoded form data app.use(bodyParser.urlencoded({ extended: true })); // Render empty form on GET request app.get('/form', (req, res) => { res.render('form', { description: '', processedResult: '' }); }); // Process form data on POST request app.post('/form', (req, res) => { // Get the user's input from the form const userInput = req.body.description; // Replace this with your actual processing logic to generate the new value const processedValue = userInput.toUpperCase(); // Example: Convert input to uppercase // Render the same form page, passing back the input and processed result res.render('form', { description: userInput, processedResult: processedValue }); }); // Start the server app.listen(3000, () => console.log('Server running on http://localhost:3000/form'));
2. Asynchronous (No-Refresh) Approach
If you want the result to appear without reloading the page, use AJAX with fetch to submit the form in the background.
Step 1: Update the Pug Template
Add IDs to the form and elements, then add a script to handle the submit event asynchronously:
form(id='processForm') p.lead textarea(style='resize:none; width:400px; height:300px;' name='description' id='description' onkeydown="if(event.keyCode===9) { event.preventDefault(); this.value += ' '; }") p button(type='submit') Process Input p.lead textarea(style='resize:none; width:400px; height:300px;' name='result' id='result' readonly) script. // Handle form submission without page refresh document.getElementById('processForm').addEventListener('submit', async (e) => { e.preventDefault(); // Stop the default form reload const inputText = document.getElementById('description').value; // Send POST request to the /form route const response = await fetch('/form', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `description=${encodeURIComponent(inputText)}` }); // Get the processed result from the server const processedResult = await response.text(); // Insert the result into the textarea document.getElementById('result').value = processedResult; });
Step 2: Adjust the Node.js Route
Modify the POST route to return just the processed value instead of rendering the template:
const express = require('express'); const bodyParser = require('body-parser'); const app = express(); app.set('view engine', 'pug'); app.use(bodyParser.urlencoded({ extended: true })); // Render the form on GET request app.get('/form', (req, res) => { res.render('form'); }); // Process input and return the result as text app.post('/form', (req, res) => { const userInput = req.body.description; // Your custom processing logic here const processedValue = userInput.split('').reverse().join(''); // Example: Reverse the input text res.send(processedValue); // Send the result back to the client }); app.listen(3000, () => console.log('Server running on http://localhost:3000/form'));
内容的提问来源于stack exchange,提问作者JooHyeong

