iT邦幫忙

2025 iThome 鐵人賽

DAY 18
0
Modern Web

使用 React + Node.js + MongoDB 打造電商網站系列 第 18

Day18 會員/管理員登入後導向個人頁面(Profile)

  • 分享至 

  • xImage
  •  

今天是鐵人賽 Day18,目標是讓會員與管理員登入後都能進入「個人頁面 (Profile)」,並在此頁面中顯示自己的基本資料。

1️⃣ 修改 App.jsx 路由設定
原本 /profile 僅限 role = user 才能進入,導致管理員登入後無法看到 Profile。
今天我們將 /profile 改成 所有登入用戶 (user + admin) 都能進入。

<Route
  path="/profile"
  element={
    <PrivateRoute>
      <Profile />
    </PrivateRoute>
  }
/>

這樣不管是一般會員或管理員,登入後都會先跳轉到個人頁面。

2️⃣ 登入頁面 (Login.jsx)
登入後統一導向 /profile,避免不同角色在登入後需要額外判斷。

const handleSubmit = async (e) => {
  e.preventDefault();
  const res = await axios.post("http://localhost:3000/api/auth/login", formData);

  setToken(res.data.token);
  setUser(res.data.user);

  // ✅ 登入後統一跳轉到 Profile
  navigate("/profile");
};

https://ithelp.ithome.com.tw/upload/images/20250930/20178893yb6oXKYTif.png

3️⃣ 個人頁面 (Profile.jsx)
Profile 頁面會讀取 localStorage 中的使用者資訊,顯示基本資料。
如果角色是 admin,則額外顯示一個「進入後台」按鈕,讓管理員能快速進入 /admin。

import React from "react";
import { getUser } from "../utils/auth";
import { useNavigate } from "react-router-dom";

export default function Profile() {
  const user = getUser();
  const navigate = useNavigate();

  return (
    <div className="bg-white shadow-md rounded-lg p-6 max-w-md mx-auto">
      <h2 className="text-2xl font-bold mb-4">個人資料</h2>
      <p><strong>帳號:</strong>{user?.username}</p>
      <p><strong>Email:</strong>{user?.email}</p>
      <p><strong>角色:</strong>{user?.role}</p>

      {user?.role === "admin" && (
        <button
          onClick={() => navigate("/admin")}
          className="mt-4 bg-orange-500 text-white px-4 py-2 rounded"
        >
          進入後台
        </button>
      )}
    </div>
  );
}

https://ithelp.ithome.com.tw/upload/images/20250930/20178893GU7NUhgrUf.png

4️⃣ 測試流程
一般會員登入 → /profile 顯示帳號、信箱、角色資訊
管理員登入 → /profile 顯示帳號、信箱、角色資訊,並多一個「進入後台」按鈕

🐛 遇到的問題與解決
問題:管理員登入後無法進入 Profile,因為 App.jsx 限制了 role="user"
解決:移除限制,讓所有登入用戶都能進入 Profile

💡 Day18 收穫

  • 完成會員/管理員登入後統一導向 Profile 頁面
  • Profile 頁面能正確顯示基本資料
  • 管理員登入後可在 Profile 點擊按鈕進入後台
  • 完成登入後的體驗優化,讓不同角色的使用者更直覺

上一篇
Day17 React 前端註冊與登入頁面 + JWT 儲存實作
下一篇
Day19 完成購物車 API:新增、修改數量與刪除商品
系列文
使用 React + Node.js + MongoDB 打造電商網站19
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言