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

Node.js+MongoDB注册API报错及bcrypt密码加密需求求助

Fixing the "Unexpected Token" (If Statement) Error

The "unexpected token" error in an if statement almost always comes down to a small syntax slip-up—think missing parentheses around your condition, unclosed curly braces, or a misplaced semicolon. Let’s use your existing code structure to show a corrected version of what your registration logic might look like, fixing common pitfalls:

var express = require('express');
var router = express.Router();
var app = express();
var bodyParser = require("body-parser");
var validator = require('validator');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); // Complete this line with your preferred setting

// Example registration route with valid if statement syntax
router.post('/register', async (req, res) => {
  const { email, password } = req.body;

  // Input validation with properly formatted if statements
  if (!validator.isEmail(email)) { // Ensure condition is wrapped in parentheses
    return res.status(400).json({ error: 'Invalid email format' });
  }

  if (!validator.isLength(password, { min: 6 })) {
    return res.status(400).json({ error: 'Password must be at least 6 characters' });
  }

  // Rest of your MongoDB save logic here...
});

Double-check these common mistakes in your code:

  • Did you wrap your if condition in ()? (e.g., if (condition) not if condition)
  • Are you missing opening/closing {} for the if block?
  • Is there a stray semicolon right after the if condition (like if (condition); { ... })?
Implementing Bcrypt Password Encryption

Adding bcrypt to hash passwords before storing them is straightforward—here’s how to integrate it into your API step by step:

Step 1: Install bcrypt

Run this command in your project directory:

npm install bcrypt

Step 2: Require bcrypt in your code

Add this line alongside your other imports:

var bcrypt = require('bcrypt');

Step 3: Hash the password before saving to MongoDB

Modify your registration route to hash the password using bcrypt. We’ll use a salt round value of 10 (a secure industry standard):

router.post('/register', async (req, res) => {
  try {
    const { email, password } = req.body;

    // Reuse your input validation logic here
    if (!validator.isEmail(email)) {
      return res.status(400).json({ error: 'Invalid email format' });
    }
    if (!validator.isLength(password, { min: 6 })) {
      return res.status(400).json({ error: 'Password must be at least 6 characters' });
    }

    // Hash the password
    const saltRounds = 10;
    const hashedPassword = await bcrypt.hash(password, saltRounds);

    // Create user object with the hashed password (never store plain text!)
    const newUser = {
      email: email,
      password: hashedPassword
    };

    // Save to your MongoDB collection (replace with your actual code)
    // Example using MongoDB driver:
    // const result = await db.collection('users').insertOne(newUser);

    res.status(201).json({ message: 'User registered successfully', userId: result.insertedId });
  } catch (err) {
    res.status(500).json({ error: 'Server error', details: err.message });
  }
});

Bonus: Verifying Passwords (For Login)

If you need to validate passwords later (e.g., during login), use bcrypt.compare() to check the submitted password against the stored hash:

router.post('/login', async (req, res) => {
  try {
    const { email, password } = req.body;
    // Fetch user from MongoDB by email
    // const user = await db.collection('users').findOne({ email: email });

    if (!user) {
      return res.status(401).json({ error: 'Invalid credentials' });
    }

    // Compare submitted password with stored hash
    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) {
      return res.status(401).json({ error: 'Invalid credentials' });
    }

    res.status(200).json({ message: 'Login successful' });
  } catch (err) {
    res.status(500).json({ error: 'Server error' });
  }
});

Wrapping async operations in try/catch blocks will help you catch and handle any unexpected errors cleanly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:34:33