You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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

  1. You're capturing form data on page load, not on submit
    Right now, your data object 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 data object 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...
    });
    
  2. Typo in input selector
    You had a mistake where playervolume was pulling values from the guildautoroleID input instead of its own—this is fixed in the code snippet above.

Backend Problems

  1. Request method mismatch
    Your frontend sends a POST request, but your backend uses app.get to handle it. GET requests don't support request bodies, so req.body will 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...
    });
    
  2. Undefined variables and broken data handling
    You're using variables like welcomeChannelID and logchannel that aren't defined anywhere—you should pull these values directly from req.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" });
        }
    });
    
  3. Invalid response sequence
    You were calling res.send(req.body) followed by res.redirect—once you send a response with res.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 23:22:44