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

MEAN新手求助:AngularJS实现登录后向仪表盘传用户名(非EJS)

Solution for Passing Username to AngularJS Dashboard Post-Login (MEAN Stack, No EJS)

Hey there! Let's walk through how to get the logged-in username over to your AngularJS dashboard without using EJS. Since you're working with Node.js/Express/MongoDB + AngularJS, here's a practical, step-by-step approach:


1. Backend Setup: Fix Login Logic & Required Middleware

First, you'll need to handle user authentication properly and track the logged-in user. The key middleware here is express-session (for session-based auth) or you can use JWT (token-based) if you prefer stateless auth.

Step 1.1: Install Dependencies

Run these commands in your backend project:

npm install express-session cors bcrypt
# If choosing JWT instead of sessions: npm install jsonwebtoken

Step 1.2: Configure Middleware in app.js

Add this to your main Express app file to enable session management and CORS (critical for cross-origin requests between your AngularJS frontend and Express backend):

const express = require('express');
const session = require('express-session');
const cors = require('cors');
const app = express();

// Allow CORS from your AngularJS frontend (update the origin to match your frontend URL)
app.use(cors({
  origin: 'http://localhost:8080', // e.g., your AngularJS dev server
  credentials: true // Required to pass cookies/session data between frontend/backend
}));

// Configure express-session to store user session data
app.use(session({
  secret: 'your-strong-unique-secret-key', // Replace with a secure secret (use env vars in production!)
  resave: false,
  saveUninitialized: false,
  cookie: {
    secure: false, // Set to true in production (only HTTPS)
    maxAge: 86400000 // Session expires after 1 day (24hrs)
  }
}));

// Parse JSON request bodies (for login data)
app.use(express.json());

Step 1.3: Update Your usercrud.js Login Function

Fix the login logic to verify the user, store their username in the session, and return a JSON response to AngularJS:

var User = require("../../schema/user/userschema"); 
var bcrypt = require('bcrypt'); 
// Uncomment if using JWT: const jwt = require('jsonwebtoken');

const userOperation = { 
  login(userObject, req, res){ // Add req parameter to access session
    const username = userObject.userid; 
    const psw = userObject.password;

    // Find user in MongoDB
    User.findOne({ userid: username })
      .then(user => {
        if (!user) {
          return res.status(401).json({ success: false, message: "User not found" });
        }
        // Verify password with bcrypt
        bcrypt.compare(psw, user.password)
          .then(isMatch => {
            if (isMatch) {
              // Option 1: Store username in session (for session-based auth)
              req.session.currentUser = { username: user.userid };
              
              // Option 2: Use JWT instead (stateless auth)
              // const token = jwt.sign({ username: user.userid }, 'your-jwt-secret', { expiresIn: '1d' });
              
              // Send success response with username to frontend
              res.status(200).json({ 
                success: true, 
                username: user.userid 
                // Uncomment if using JWT: token: token
              });
            } else {
              res.status(401).json({ success: false, message: "Invalid password" });
            }
          })
          .catch(err => res.status(500).json({ success: false, message: err.message }));
      })
      .catch(err => res.status(500).json({ success: false, message: err.message }));
  }
};

module.exports = userOperation;

Don't forget to update your login route to pass the req object:

// Example login route in your Express app
app.post('/api/login', (req, res) => {
  userOperation.login(req.body, req, res);
});

2. Frontend AngularJS Setup: Receive & Store Username

In your AngularJS app, handle the login response, store the username, and access it in the dashboard.

Step 2.1: Login Controller

Add logic to send login data, handle the response, and store the username (use $rootScope or a dedicated auth service for better scalability):

angular.module('yourAppName')
.controller('LoginController', ['$scope', '$http', '$location', '$rootScope', function($scope, $http, $location, $rootScope) {
  $scope.login = function() {
    // Send login request to Express backend
    $http.post('http://localhost:3000/api/login', {
      userid: $scope.usernameInput,
      password: $scope.passwordInput
    }, { withCredentials: true }) // Required to send session cookies
    .then(response => {
      if (response.data.success) {
        // Store username in $rootScope to access across views
        $rootScope.currentUser = response.data.username;
        
        // Optional: Store in localStorage for persistent login (across page reloads)
        localStorage.setItem('currentUser', response.data.username);
        
        // Redirect to dashboard
        $location.path('/dashboard');
      } else {
        alert(response.data.message);
      }
    })
    .catch(err => {
      console.error('Login failed:', err);
      alert('Something went wrong during login');
    });
  };
}]);

Step 2.2: Dashboard Controller

Access the stored username in your dashboard controller to display it:

angular.module('yourAppName')
.controller('DashboardController', ['$scope', '$rootScope', function($scope, $rootScope) {
  // Get username from $rootScope
  $scope.loggedInUser = $rootScope.currentUser;
  
  // Or retrieve from localStorage if using persistent storage
  // $scope.loggedInUser = localStorage.getItem('currentUser');
}]);

Step 2.3: Display Username in Dashboard Template

In your AngularJS dashboard HTML, use interpolation to show the username:

<div class="dashboard-header">
  Welcome, {{ loggedInUser }}!
</div>

Key Notes

  • Session vs JWT: Use express-session if you want server-side session management, or JWT for stateless auth (great for scaling across multiple servers).
  • Security: Always use HTTPS in production, store secrets in environment variables (never hardcode them), and sanitize user input to prevent attacks.
  • Auth Service: For larger apps, create a dedicated AngularJS auth service instead of relying on $rootScope to manage user state more cleanly.

内容的提问来源于stack exchange,提问作者Mani Kant Tiwari

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:07:43