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

AWS Amplify React JS:未注册用户触发Auth报错,需添加注册逻辑

解决方案

核心问题修正与优化

  1. 异步代码位置错误:原代码将await Auth.currentAuthenticatedUser()写在组件外部,不符合React组件执行逻辑,且未处理未认证异常,需移至组件内部的useEffect钩子中并添加try/catch捕获错误。
  2. 冗余数据处理:你之前用JSON.stringify(attributes.email).replace(/"/g, '')完全没必要,attributes中的字段本身就是字符串类型,直接取值即可。
  3. 未认证流程触发:通过状态管理控制UI渲染,已认证用户显示聊天界面,未认证用户显示注册/登录表单,调用Amplify Auth的注册方法完成用户创建。

完整示例代码

import { useState, useEffect } from 'react';
import { Auth } from 'aws-amplify';

const App = () => {
  // 管理用户认证状态和用户信息
  const [user, setUser] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  // 注册/登录表单状态
  const [authForm, setAuthForm] = useState({
    username: '',
    email: '',
    password: '',
    name: ''
  });

  // 组件挂载时检查用户认证状态
  useEffect(() => {
    checkAuthStatus();
  }, []);

  // 检查用户是否已认证
  const checkAuthStatus = async () => {
    try {
      const authenticatedUser = await Auth.currentAuthenticatedUser();
      const { attributes } = authenticatedUser;
      // 直接读取Cognito用户属性,无需JSON处理
      setUser({
        authoremail: attributes.email,
        authorid: attributes.sub,
        authorname: attributes.name,
        channelid: attributes.sub
      });
    } catch (err) {
      // 捕获未认证错误,切换到注册/登录状态
      if (err.message === 'The user is not authenticated') {
        setUser(null);
      } else {
        console.error('认证检查出错:', err);
      }
    } finally {
      setIsLoading(false);
    }
  };

  // 处理表单输入变化
  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setAuthForm(prev => ({ ...prev, [name]: value }));
  };

  // 触发用户注册流程
  const handleSignup = async () => {
    try {
      const { username, email, password, name } = authForm;
      // 调用Amplify Auth注册接口,属性需与Cognito用户池配置一致
      await Auth.signUp({
        username,
        password,
        attributes: {
          email,
          name
        }
      });
      alert('注册成功,请检查邮箱完成验证');
    } catch (err) {
      alert(`注册失败: ${err.message}`);
    }
  };

  // 处理用户登录(注册后需登录)
  const handleLogin = async () => {
    try {
      const { username, password } = authForm;
      const loggedInUser = await Auth.signIn(username, password);
      const { attributes } = loggedInUser;
      setUser({
        authoremail: attributes.email,
        authorid: attributes.sub,
        authorname: attributes.name,
        channelid: attributes.sub
      });
    } catch (err) {
      alert(`登录失败: ${err.message}`);
    }
  };

  // 加载状态显示
  if (isLoading) {
    return <div>加载中...</div>;
  }

  return (
    <div className="App">
      {user ? (
        // 已认证用户显示聊天界面
        <div>
          <h1>欢迎回来,{user.authorname}</h1>
          <p>用户ID: {user.authorid}</p>
          <p>邮箱: {user.authoremail}</p>
          {/* 此处添加你的聊天机器人UI组件 */}
        </div>
      ) : (
        // 未认证用户显示注册/登录表单
        <div className="auth-form">
          <h2>注册/登录</h2>
          <div className="form-group">
            <label>用户名:</label>
            <input
              type="text"
              name="username"
              value={authForm.username}
              onChange={handleInputChange}
              required
            />
          </div>
          <div className="form-group">
            <label>邮箱:</label>
            <input
              type="email"
              name="email"
              value={authForm.email}
              onChange={handleInputChange}
              required
            />
          </div>
          <div className="form-group">
            <label>姓名:</label>
            <input
              type="text"
              name="name"
              value={authForm.name}
              onChange={handleInputChange}
              required
            />
          </div>
          <div className="form-group">
            <label>密码:</label>
            <input
              type="password"
              name="password"
              value={authForm.password}
              onChange={handleInputChange}
              required
            />
          </div>
          <button onClick={handleSignup}>注册</button>
          <button onClick={handleLogin}>登录</button>
        </div>
      )}
    </div>
  );
};

export default App;

关键说明

  • 认证状态检查:通过useEffect在组件初始化时执行认证检查,用try/catch精准捕获未认证异常,避免程序崩溃。
  • 注册流程:调用Auth.signUp方法时,需确保传入的用户属性(如name、email)与Cognito用户池配置的属性完全匹配。
  • 状态驱动UI:用user状态控制界面切换,已认证用户显示聊天功能,未认证用户显示注册/登录入口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 15:43:25