Vite+React前端项目出现uncaught TypeError错误,寻求解决方案
问题描述
近期在基于Vite构建的JavaScript前端项目开发中,突然触发错误,尝试修复并添加代码后又出现新错误。相关错误信息:
uncaught TypeError: Cannot read properties of undefined (reading 'prototype')
代码片段
import { useState } from 'react' import './App.css' import { response } from 'express' function App() { const [Password, SetPassword] = useState('') const [Username, SetUsername] = useState('') const onSubmit = () => { fetch('http://localhost:3000', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ Username: Username, // No need to wrap Username in an object Password: Password }) }) .then(response => { if (response.status == 200){ alert('Matched!') } }) .catch(error => { console.error(response) }) } return ( <> <div class='mainDiv --centered'> <input class='UsernameBox --verticallycentered' placeholder='Username/Email/Phone' value={Username} onChange={(e) => SetUsername(e.target.value)}></input> <input class='PasswordBox --verticallycentered' placeholder='Password' value={Password} onChange={(e) => SetPassword(e.target.value)}></input> <h4 className='ErrorThingy'>Passwords can only contain Letters, numbers and symbols</h4> <button onClick={onSubmit} className='LoginBtn --centered'> Log in</button> </div> </> ) } export default App
问题分析与解决方案
核心错误原因
- 错误引入后端模块:前端项目无需引入Node.js后端框架
express,你导入的{ response } from 'express'会导致Vite在浏览器环境中加载后端模块,直接触发Cannot read properties of undefined (reading 'prototype')错误——express依赖Node.js特定API,无法在浏览器中正常运行。 - catch块作用域错误:
catch回调里的response未在当前作用域定义,此处应该打印捕获到的error而非未定义的response。
修复步骤
- 移除无效导入:删除
import { response } from 'express'这一行。 - 修正错误日志:将
catch块中的console.error(response)改为console.error(error)。 - (可选)统一React属性:React中需用
className替代原生HTML的class属性,避免控制台警告,比如把<div class='mainDiv --centered'>修改为<div className='mainDiv --centered'>。
修复后代码
import { useState } from 'react' import './App.css' function App() { const [Password, SetPassword] = useState('') const [Username, SetUsername] = useState('') const onSubmit = () => { fetch('http://localhost:3000', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ Username: Username, Password: Password }) }) .then(response => { if (response.status === 200){ alert('Matched!') } }) .catch(error => { console.error(error) }) } return ( <> <div className='mainDiv --centered'> <input className='UsernameBox --verticallycentered' placeholder='Username/Email/Phone' value={Username} onChange={(e) => SetUsername(e.target.value)} /> <input className='PasswordBox --verticallycentered' placeholder='Password' value={Password} onChange={(e) => SetPassword(e.target.value)} /> <h4 className='ErrorThingy'>Passwords can only contain Letters, numbers and symbols</h4> <button onClick={onSubmit} className='LoginBtn --centered'> Log in</button> </div> </> ) } export default App
内容的提问来源于stack exchange,提问作者Char
相关产品推荐
相关产品推荐

