如何将EJS页面修改后的表单数据发送至Node.js后端?
Hey there, let's break down the issues in your code step by step—you've got a couple of key mistakes on both frontend and backend that are causing old, initial data to be sent instead of the updated values users enter.
Frontend Problems
You're capturing form data on page load, not on submit
Right now, yourdataobject is created as soon as the page loads, so it only holds the initial values from the EJS template. When users edit inputs and click "Save Changes", you're still sending that original data instead of fetching the current input values.Fix this by moving the
dataobject definition inside your click handler, so it grabs fresh values when the button is clicked:$('.btn-primary.btn').click(function() { // Capture latest input values at the time of submission let data = { prefix: $('#Prefix').val(), welcomeChannelID: $('#welcomeChannelID').val(), logchannelID: $('#logchannelID').val(), voicelogchannelID: $('#voicelogchannelID').val(), defaultchannelID: $('#defaultchannelID').val(), guildautoroleID: $('#guildautoroleID').val(), playervolume: $('#playervolume').val(), // Fixed: was incorrectly using guildautoroleID selector here }; // Rest of your AJAX code here... });Typo in input selector
You had a mistake whereplayervolumewas pulling values from theguildautoroleIDinput instead of its own—this is fixed in the code snippet above.
Backend Problems
Request method mismatch
Your frontend sends aPOSTrequest, but your backend usesapp.getto handle it. GET requests don't support request bodies, soreq.bodywill be empty/undefined, and you're likely falling back to uninitialized variables (which might default to old values).Change your route to use
app.post:app.post("/dashboard/:guildID/set", checkAuth, async (req, res) => { // Rest of your code here... });Undefined variables and broken data handling
You're using variables likewelcomeChannelIDandlogchannelthat aren't defined anywhere—you should pull these values directly fromreq.body. Also, your channel ID formatting logic is unnecessary and error-prone. Let's clean that up:app.post("/dashboard/:guildID/set", checkAuth, async (req, res) => { // Updated for Discord.js v12+ (use cache.get instead of get) const guild = client.guilds.cache.get(req.params.guildID); if (!guild) return res.status(404).send("Guild not found"); const isManaged = guild.members.cache.has(req.user.id) ? guild.members.cache.get(req.user.id).permissions.has("MANAGE_GUILD") : false; if (!isManaged && !req.session.isAdmin) return res.redirect("/"); // Helper to sanitize input values const sanitizeInput = (str) => str?.replace(/[^0-9a-zA-Z_]/g, '') || ''; try { await db.collection('guilds').doc(guild.id).update({ prefix: req.body.prefix, welcomeChannelID: sanitizeInput(req.body.welcomeChannelID), logchannel: sanitizeInput(req.body.logchannelID), voicelogchannel: sanitizeInput(req.body.voicelogchannelID), guildautorole: sanitizeInput(req.body.guildautoroleID), defaultchannelID: sanitizeInput(req.body.defaultchannelID), playervolume: req.body.playervolume, }); // AJAX requests don't follow redirects automatically—send a success response instead res.status(200).send({ success: true, message: "Settings updated successfully" }); } catch (err) { console.error("Failed to update settings:", err); res.status(500).send({ success: false, message: "Failed to save changes" }); } });Invalid response sequence
You were callingres.send(req.body)followed byres.redirect—once you send a response withres.send, the response cycle ends, so the redirect will never run. For AJAX requests, handle the redirect on the frontend:success: function(response) { console.log(response.message); // Redirect user to the dashboard page after successful save window.location.href = `/dashboard/${guildID}`; },
Critical Setup Note
Make sure you have JSON parsing middleware enabled in your Node.js app—otherwise req.body will be undefined:
app.use(express.json());
内容的提问来源于stack exchange,提问作者ETHYT

