所以,我有一个后端身份验证,它向我展示了邮递员和 Mongo 中的用户数据。我在控制台 xhr.js:177 POST http://localhost:3000/api/auth/register 404 (Not Found)
中有一个错误,我想我通过在 post 方法中添加“"http://localhost:5000/api/auth/register"而不是仅 api/auth/register
来修复它,但是现在,当我尝试注册时,我收到此错误 Unhandled Rejection (TypeError): Cannot read property 'data' of undefined
。如果有人能告诉我为什么会出现这种情况以及如何解决,我将不胜感激。谢谢
import axios from "axios";
import { Link } from "react-router-dom";
const Register = ({ history }) => {
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [confirmpassword, setConfirmPassword] = useState("");
const [error, setError] = useState("");
const registerHandler = async (e) => {
e.preventDefault();
const config = {
header: {
"Content-Type": "application/json",
},
};
if (password !== confirmpassword) {
setPassword("");
setConfirmPassword("");
setTimeout(() => {
setError("");
}, 5000);
return setError("Passwords do not match");
}
try {
const { data } = await axios.post(
"http://localhost:5000/api/auth/register",
{
username,
email,
password,
},
config
);
localStorage.setItem("authToken", data.token);
history.push("/");
} catch (error) {
setError(error.response.data.error);
setTimeout(() => {
setError("");
}, 5000);
}
};
return (
<div className="register-screen">
<form onSubmit={registerHandler} className="register-screen__form">
<h3 className="register-screen__title">Register</h3>
{error && <span className="error-message">{error}</span>}
<div className="form-group">
<label htmlFor="name">Username:</label>
<input
type="text"
required
id="name"
placeholder="Enter username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor="email">Email:</label>
<input
type="email"
required
id="email"
placeholder="Email address"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password:</label>
<input
type="password"
required
id="password"
autoComplete="true"
placeholder="Enter password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor="confirmpassword">Confirm Password:</label>
<input
type="password"
required
id="confirmpassword"
autoComplete="true"
placeholder="Confirm password"
value={confirmpassword}
onChange={(e) => setConfirmPassword(e.target.value)}
/>
</div>
<button type="submit" className="btn btn-primary">
Register
</button>
<span className="register-screen__subtext">
Already have an account? <Link to="/login">Login</Link>
</span>
</form>
</div>
);
};
export default Register;
答案 0 :(得分:1)
您需要检查 error.response
是否存在。似乎在您的情况下未定义。
if (error.response) {
setError(error.response.data.error);
}
setTimeout(() => {
setError("");
}, 5000);
这将帮助您解决此错误 Cannot read property 'data' of undefined
,但要回答您收到 xhr.js:177 POST http://localhost:3000/api/auth/register 404 (Not Found)
的原因,我们需要更多信息。您的服务器上没有 /api/auth/register
处理程序。