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

NodeJS+React JWT用户认证问题:查询结果返回[object object]无法取密码

Fixing Your Node.js JWT Authentication Issues

Hey there, let's work through your JWT auth problems together—there are a couple of key issues here that are throwing things off, plus a small logging confusion.

First: The "[object Object]" Logging Red Herring

Your console.log('result = ' + result[0]) in userServices.js is misleading you! When you concatenate an object with a string using +, JavaScript converts the object to the string [object Object]. This doesn't mean your callback is returning that string—it's still passing the actual user object to the controller. To see the full user data in logs, change that line to:

console.log('result =', result[0]); // Uses comma instead of + to log the object properly

Second: Critical Password Comparison Logic Reversal

This is the main issue breaking your auth flow! In userController.js, your compareSync check is backwards:

  • compareSync(plainTextPassword, hashedPassword) returns true when the passwords match
  • But right now, you're only generating a token if !result (i.e., when passwords DON'T match)

That's why you're never getting the valid token, and it looks like you can't access the user password (you actually can—your logic is just skipping the correct path).

Third: Invalid Logging in the Else Block

Your line console.log('password' + result.password) will throw an error because when result is true (password match), it's a boolean value, not an object—so result.password doesn't exist.

Fixed Code Snippets

Updated userServices.js

const db = require('./../../db-connection/connection');

const userAuth = (params, callback) => {
  db.query(`SELECT * FROM Users WHERE email = ?`, [params.email], (error, result, fields) => {
    if (error) {
      console.error('DB query error:', error);
      return callback(error);
    }
    // Log the user object correctly
    console.log('Fetched user:', result[0]);
    callback(null, result[0]);
  });
};

module.exports = { userAuth }; // Make sure you're exporting this properly

Updated userController.js

const { userAuth } = require('./UserServices');
const { compareSync } = require('bcrypt');
const { sign } = require('jsonwebtoken');

const userLoginAuth = (req, res) => {
  const body = req.body;
  
  userAuth(body, (error, results) => {
    if (error) {
      console.error('Auth service error:', error);
      return res.status(500).json({ success: 0, error: 'Server error' });
    }
    if (!results) {
      return res.json({ success: 0, data: 'Invalid email or password' });
    }

    // Correct password comparison: check if passwords MATCH
    const passwordMatch = compareSync(body.password, results.password);
    if (passwordMatch) {
      // Remove password from the response data for security
      results.password = undefined;
      const jsontoken = sign({ result: results }, 'choegyel123', { expiresIn: '1h' });
      return res.json({ 
        success: 1, 
        message: 'Login successful', 
        token: jsontoken 
      });
    } else {
      // Passwords don't match
      return res.json({ success: 0, error: 'Invalid email or password' });
    }
  });
};

module.exports = { userLoginAuth };

Key Fixes Recap

  1. Fixed logging to properly display the user object instead of [object Object]
  2. Reversed the password comparison logic to generate a token only when passwords match
  3. Removed invalid logging that would throw an error
  4. Added proper error handling for database/server errors
  5. Ensured we only return the token when authentication succeeds

Once you implement these changes, your controller will correctly access the user's password from the database result, validate it, and issue a JWT token on successful login.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 18:42:38