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

Express JS/MongoDB注册功能异常:页面持续刷新及端口占用问题

Hey, let's figure out why your registration form is causing endless refreshes and fix those issues step by step!

1. The Root Cause of Endless Refreshes: Mismatched Schema Fields & Missing Error Responses

First off, the biggest issue here is a field mismatch between your User Schema and the data you're trying to save, which breaks the user creation process and leaves the browser hanging.

Look at your user.js Schema: you defined a required field called fullName, but in your users.js POST handler, you're pulling name from the request body and passing that to the new User() constructor. This means when you call newUser.save(), MongoDB will throw an error because the required fullName field is missing.

Worse, your catch block only logs the error to the console and doesn't send any response back to the browser. The request stays in a pending state, and browsers often retry such requests, leading to the endless refresh loop you're seeing.

Fix: Align the Schema and Request Data

You have two options here:

  • Option 1: Update the Schema to match your form field
    // user.js
    const userSchema = new mongoose.Schema({
      name: { // Change `fullName` to `name`
        type: String,
        required: true
      },
      email: {
        type: String,
        required: true
      },
      password: {
        type: String,
        required: true
      },
      date: {
        type: Date,
        default: Date.now
      }
    });
    
  • Option 2: Map the request name to the Schema's fullName
    // users.js
    const newUser = new User({ 
      fullName: name, // Map the incoming `name` to `fullName`
      email, 
      password 
    });
    

Add Proper Error Handling for Save Failures

Update the save() catch block to send a response to the browser instead of just logging:

newUser
  .save()
  .then(user => {
    req.flash(
      'success_msg',
      'You are now registered and can log in'
    );
    res.redirect('/users/login');
  })
  .catch(err => {
    console.log(err);
    errors.push({ msg: 'Failed to create your account. Please try again.' });
    res.render('register', { errors, name, email, password, password2 });
  });

2. Fix the Mongoose Connection Issue

In your app.js, you defined the db variable with your MongoDB URI but passed an empty string to mongoose.connect(). While you said the connection log shows success (likely connecting to a default local instance), this is unreliable and could cause unexpected behavior later.

Update the connection code to use your db variable and add proper error handling:

// app.js
mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('MongoDB Connected...'))
  .catch(err => console.error('MongoDB connection failed:', err));

3. Resolve the EADDRINUSE Port Error

This error just means port 8000 is already being used by another process. If it pops up again:

  • Windows: Open Command Prompt and run:
    netstat -ano | findstr :8000
    # Find the PID number, then kill the process
    taskkill /PID <your-pid-number> /F
    
  • Linux/macOS: Open Terminal and run:
    lsof -i :8000
    # Kill the process with the PID
    kill -9 <your-pid-number>
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 12:47:42