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

点击HTML提交按钮时通过Mongoose向MongoDB存储数据失效问题求助

问题核心原因排查

  • 最根本的运行环境错误:Mongoose是仅能在Node.js服务端运行的MongoDB操作库,你把包含Mongoose逻辑的js文件直接引入前端HTML中,浏览器无法识别require、mongoose.connect等Node.js专属API,代码从根本上无法运行。同时将数据库连接URI直接暴露在前端代码中会导致数据库完全失控,任何人都可以直接操作你所有的数据,存在极高安全风险。
  • 表单默认行为未阻止:你绑定点击事件的是表单的submit类型按钮,点击后会触发表单默认的提交刷新行为,就算你逻辑是对的,代码还没执行完成页面就会刷新,操作会被中断。
  • 前后端职责混淆:数据库操作属于后端逻辑,不能直接和前端代码耦合,你需要先搭建后端服务,前端仅负责收集用户输入、向后端发送请求,由后端完成数据库写入操作。

修复方案

第一步:搭建Node.js后端服务

  1. 先初始化项目安装依赖:
npm init -y
npm install express mongoose cors
  1. 编写后端入口文件app.js,将Mongoose逻辑全部移到后端:
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const User = require("./models/user")
const app = express()
const port = 3000

// 连接数据库
const db_URI = '你的数据库连接串'
mongoose.connect(db_URI)
  .then(() => console.log('数据库连接成功'))
  .catch(err => console.log('数据库连接失败', err))

// 解析请求参数
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

// 注册接口
app.post('/register', async (req, res) => {
  try {
    const { name, email, password } = req.body
    const user = new User({ name, email, password })
    await user.save()
    res.status(200).json({ code: 0, msg: '注册成功' })
  } catch (err) {
    res.status(500).json({ code: 1, msg: '注册失败', error: err.message })
  }
})

app.listen(port, () => console.log(`后端服务运行在 http://localhost:${port}`))

第二步:修改前端代码

删除前端引入的db_processes.js,新增前端请求逻辑,同时阻止表单默认提交行为:

<!DOCTYPE html>
<html>
<head>
    <title>SIGN UP HERE</title>
</head>
<body>
    <form id="register-form">
        <div>
            <label id="name-lbl">Name: </label>
            <input type="text" name="nick" placeholder="Your nickname here" required>
        </div>
        <div>
            <label>E-mail: </label>
            <input type="email" name="email" placeholder="Your email here" required>
        </div>
        <div>  
            <label>Password: </label>
            <input type="password" name="pwd" placeholder="Your password here" required>
        </div>
        <div>
            <label>Confirm password: </label>
            <input type="password" name="confirmPwd" placeholder="Confirm your password" required>
        </div>
        <button type="submit" id="submit-btn">Submit</button>
    </form>

    <script>
        const form = document.getElementById('register-form')
        form.addEventListener('submit', async (e) => {
            // 阻止表单默认提交刷新行为
            e.preventDefault()
            // 收集表单数据
            const name = form.querySelector('[name="nick"]').value
            const email = form.querySelector('[name="email"]').value
            const password = form.querySelector('[name="pwd"]').value
            const confirmPwd = form.querySelector('[name="confirmPwd"]').value

            // 简单校验
            if(password !== confirmPwd) {
                alert('两次输入的密码不一致')
                return
            }

            // 向后端发请求
            try {
                const res = await fetch('http://localhost:3000/register', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ name, email, password })
                })
                const data = await res.json()
                if(data.code === 0) {
                    alert('注册成功')
                    form.reset()
                } else {
                    alert('注册失败:' + data.msg)
                }
            } catch(err) {
                alert('请求失败:' + err.message)
            }
        })
    </script>
</body>
</html>

额外注意事项

  • 确保你定义的User模型的字段名和你传入的字段完全匹配,如果Schema里定义的用户名字段是username不是name,存储会失败
  • 不要明文存储密码,后续可以引入bcrypt对密码加密后再存入数据库
  • 数据库连接串不要硬编码在代码里,可以用dotenv库读取环境变量存储敏感信息

内容的提问来源于stack exchange,提问作者statist31

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:06:02