微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

REACT JS:未处理的拒绝TypeError:无法读取未定义的属性“数据”

如何解决REACT JS:未处理的拒绝TypeError:无法读取未定义的属性“数据”

在提交表单内所需的详细信息后,我正在请求帮助解决以下错误,该错误发生在我的登录表单中的 React js 前端。

未处理的拒绝(类型错误):无法读取未定义的属性“数据”

这是 Chrome 和 Chrome 控制台上显示错误的屏幕截图

image

它发生在我点击登录表单的提交按钮后尝试登录但在我的后端,因为我正在使用 MERN 应用程序,它实际上提交了数据正确并验证它,我收到 200 成功消息,这是我的 VS Code 控制台的屏幕截图。

image

我认为该错误主要发生在我的 React 前端 并且我的后端运行顺利,我尝试在 Internet 上查看该错误,但无法获得具体的修复不得不用尝试和捕捉来修复它,但我最终没有成功锻炼。

下面的代码是我的 Login.js 上的特定代码,它带来了错误

  241 |           password1: '',242 |           textChange: 'Sign In'
  243 |         });
> 244 |         toast.error(err.response.data.errors); //This is the line where React is complaining of the error
      | ^  245 |       });
  246 | } else {
  247 |   toast.error('Please fill all fields');

我的 Login.js 文件的完整代码如下;

import React,{ useState } from 'react'
import authSvg from '../assets/login.svg'
import { ToastContainer,toast } from 'react-toastify';
import { authenticate,isAuth } from '../helpers/auth';
import axios from 'axios';
// import { Redirect } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';


const Login = ({ history }) => {
    const [formData,setFormData] = useState({
        email: '',password1: '',textChange: 'Sign In'
    })

    const {email,password1,textChange } = formData
    // Handle change inputs
    const handleChange = text => e => {
        // console.log(username,email,phone,firstName,lastName,password)
        setFormData({...formData,[text]: e.target.value})
    }

    // Submit data to backend
    const handleSubmit = e => {
        console.log(process.env.REACT_APP_API_URL);
        e.preventDefault()
        if (email && password1){
            setFormData({ ...formData,textChange: 'Submitting' });
            axios.post(`${process.env.REACT_APP_API_URL}/login`,{
                email,password: password1
            }).then(res => {
                authenticate(res,() => {
                    setFormData({
                        ...formData,email: '',textChange: 'Submitted'
                    })
                    console.log(res.data)
                })
                  // if authenticate but not admin redirect to / private
                  // if admin redirect to /admin
              isAuth() && isAuth().role === 'admin'
                  ?history.push('/')
                  :history.push('/register'); //Here for Now am testing the routing with the available routes I have at the moment
              toast.success(`hey ${res.data.user.username},Welcome back!`);
                  toast.success(`hey ${res.data.user.username},Welcome back!`);
                })
                .catch(err => {
                  setFormData({
                    ...formData,textChange: 'Sign In'
                  });
                  toast.error(err.response.data.errors); //This is the line where I get the React **undefined** Error
                });
          } else {
            toast.error('Please fill all fields');
          }
        };

    const navigate = useNavigate();

    return (
        <div className='min-h-screen bg-gray-100 text-gray-900 flex justify-center'>
          {/* {isAuth() ? <Redirect to='/' /> : null} */}
        {isAuth() ? <navigate to='/' /> : null}
        <ToastContainer />
        <div className='max-w-screen-xl m-0 sm:m-20 bg-white shadow sm:rounded-lg flex justify-center flex-1'>
          <div className='lg:w-1/2 xl:w-5/12 p-6 sm:p-12'>
            <div className='mt-12 flex flex-col items-center'>
              <h1 className='text-2xl xl:text-3xl font-extrabold'>
                Sign In for Ntuma
              </h1>
  
              <form
                className='w-full flex-1 mt-8 text-indigo-500'
                onSubmit={handleSubmit}
              >
                <div className='mx-auto max-w-xs relative '>
                  <input
                    className='w-full px-8 py-4 rounded-lg font-medium bg-gray-100 border border-gray-200 placeholder-gray-500 text-sm focus:outline-none focus:border-gray-400 focus:bg-white mt-5'
                    type='email'
                    placeholder='Email'
                    onChange={handleChange('email')}
                    value={email}
                  />
                  <input
                    className='w-full px-8 py-4 rounded-lg font-medium bg-gray-100 border border-gray-200 placeholder-gray-500 text-sm focus:outline-none focus:border-gray-400 focus:bg-white mt-5'
                    type='password'
                    placeholder='Password'
                    onChange={handleChange('password1')}
                    value={password1}
                  />
                  <button
                    type='submit'
                    className='mt-5 tracking-wide font-semibold bg-indigo-500 text-gray-100 w-full py-4 rounded-lg hover:bg-indigo-700 transition-all duration-300 ease-in-out flex items-center justify-center focus:shadow-outline focus:outline-none'
                  >
                    <i className='fas fa-user-plus fa 1x w-6  -ml-2' />
                    <span className='ml-3'>{textChange}</span>
                  </button>
                  <a
                    href='/users/password/forget'
                    className='no-underline hover:underline text-indigo-500 text-md text-right absolute right-0  mt-2'
                >
                  Forget password?
                </a>
                </div>
                <div className='my-12 border-b text-center'>
                  <div className='leading-none px-2 inline-block text-sm text-gray-600 tracking-wide font-medium bg-white transform translate-y-1/2'>
                    Or Sign Up
                  </div>
                </div>
                <div className='flex flex-col items-center'>
                  <a
                    className='w-full max-w-xs font-bold shadow-sm rounded-lg py-3
             bg-indigo-100 text-gray-800 flex items-center justify-center transition-all duration-300 ease-in-out focus:outline-none hover:shadow focus:shadow-sm focus:shadow-outline mt-5'
                    href='/register'
                    target='_self'
                  >
                    <i className='fas fa-sign-in-alt fa 1x w-6  -ml-2 text-indigo-500' />
                    <span className='ml-4'>Log In</span>
                  </a>
                </div>
              </form>
            </div>
          </div>
          <div className='flex-1 bg-indigo-100 text-center hidden lg:flex'>
            <div
              className='m-12 xl:m-16 w-full bg-contain bg-center bg-no-repeat'
              style={{ backgroundImage: `url(${authSvg})` }}
            ></div>
          </div>
        </div>
        ;
      </div>
    );
};

export default Login

这些是我后端的控制器,我用于我的 Login.js 前端表单,称为 loginController 但用于后端 似乎没问题,因为我在 VS Code 控制台 上收到了 200 Success 消息,如上面的图片

所示>
exports.loginController = (req,res) => {
  const { email,password } = req.body
  const errors = validationResult(req)

  // Validation to req.body we will create custom validation in seconds
  if (!errors.isEmpty()) {
    const firstError = errors.array().map((error) => error.msg)[0];
    return res.status(422).json({
      errors: firstError,});
  } else {
    // Check if user exist
    RegistersignUp.findOne({
      email
    }).exec((err,user) => {
      if (err || !user) {
        return res.status(400).json({
          errors: 'User with that email does not exist. Please Signup'
        });
      }
    
      // Authenticate
      if (!user.authenticate(password)) {
        return res.status(400).json({
          errors: 'Email and password do not match'
        })
      }

      // Generate Token
      const token = jwt.sign(
        {
          _id: user._id
        },process.env.JWT_SECRET,{
          expiresIn: '7d' // Token valid in 7 day you can set remember in front and set it for 30 days
        }
      )
      const {
        _id,username,role,} = user
      return res.json({
        token,user: {
          _id,role
        }
      })
    })
  }
}

在我的代码添加 console.log(err) 后,这是 Chrome 控制台中发生的输出错误信息显示

TypeError 无法读取未定义的属性 'push'

下面是 Chrome console.log 输出的屏幕截图

Screenshot

解决方法

首先,您需要检查 err 对象中的数据。

在成功案例中,您正在检查 res.data.user.username 在调用 err 之前尝试查看内部 err.response.data.errors,显然 err.response 是未定义的。

,

在 toast 中传递错误消息之前,请通过执行控制台检查。

.catch((error) => {
    if (error.response) {
      // Request made and server responded
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error',error.message);
    }
});
,

不是直接一个答案,任何人都可以自由纠正我,因为我不是 React.js 的专家,但因为我设法让一些事情发挥作用以为我现在应该发布我的错误来自以下内容;

首先,我在我的代码中使用了 React Router v6

首先在路由中我需要添加这两条路径;

  { path: '/private',element: <PrivateRoute /> },{ path: '/admin',element: <AdminRoute  /> },

第二个是转换 history.push,因为 React 不再支持它。

这意味着我必须通过以下方式使用导航将 history.push 转换为 useNavigate;

      ?history.push('/admin')
      :history.push('/private');

转换后的代码如下不要忘记导入useNavigate import { useNavigate } from 'react-router-dom'; 然后将其称为 const navigate = useNavigate();

          // if authenticate but not admin redirect to / private
          // if admin redirect to /admin
          isAuth() && isAuth().role === 'admin'
              // ?history.push('/admin')
              // :history.push('/private');
              ?navigate('/admin')
              :navigate('/private')
          toast.success(`Hey ${res.data.user.username},Welcome back!`);
        })

正如您从我的图像屏幕截图中看到的,我的错误已清除,Chrome 控制台也已清除,如果您可以放大网址栏你可以注意到路由成功从/login更改为/privateimage

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。