当我从axios获取数据时,我得到了上述错误,当所有的验证都正确时,我得到了数据,但是当我试图发送错误的数据时,我得到了上述错误。
import React from 'react'
import { TextField, Button } from '@mui/material';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import GoogleIcon from '@mui/icons-material/Google';
import FacebookIcon from '@mui/icons-material/Facebook';
import { Link } from "react-router-dom";
import "../styles/home.css"
import useInputState from "../hooks/useInputState"
import axios from 'axios';
function Login() {
const [username, updateUsername, resetUsername] = useInputState("")
const [password, updatePassword, resetPassword] = useInputState("")
const HOST = "http://localhost:8080"
const handleSubmit = async (evt) => {
evt.preventDefault()
const config = { headers: { 'Content-Type': 'application/json' } }
const data = JSON.stringify({ username, password })
console.log(data)
const response = await axios.post(`${HOST}/api/auth/login`, data, config)
console.log(response.data)
resetUsername()
resetPassword()
// if (resp.data.success) {
// console.log("redirecting to oppp")
// } else {
// alert("invalid credentials")
// }
}
return (
<div>
<div className="container mt-5 addnotes" >
<Button className="mb-4" variant="text" color="secondary" startIcon={<ArrowBackIcon />} component={Link} to="/" style={{ textTransform: "none", fontFamily: "'Poppins', sans-serif" }}>Home</Button>
<h2 style={{ fontWeight: "Bold" }}>Login</h2>
<p className="mb-4">Sign in on the internal platform</p>
<div className="d-flex">
<Button size="large" fullWidth className="mb-4 me-4" variant="contained" color="primary" startIcon={<FacebookIcon />} component={Link} to="/" style={{ textTransform: "none", fontSize: "1.1rem", color: "White", fontFamily: "'Poppins', sans-serif" }}>Login with Facebook</Button>
<Button size="large" fullWidth className="mb-4" variant="contained" color="error" startIcon={<GoogleIcon />} component={Link} to="/" style={{ textTransform: "none", fontSize: "1.1rem", color: "White", fontFamily: "'Poppins', sans-serif" }}>Login with Google</Button>
</div>
<p className="mb-4 d-flex justify-content-center">or login with username and password</p>
<form onSubmit={handleSubmit}>
<div className="mb-4">
<TextField value={username} onChange={updateUsername} inputProps={{ minLength: 1 }} color="secondary" label="Username" variant="outlined" fullWidth required style={{ textTransform: "none", fontFamily: "'Poppins', sans-serif", fontSize: "1.1rem" }} />
</div>
<div className="mb-4">
<TextField type="password" value={password} onChange={updatePassword} inputProps={{ minLength: 1 }} color="secondary" label="Password" variant="outlined" fullWidth required style={{ textTransform: "none", fontFamily: "'Poppins', sans-serif", fontSize: "1.1rem" }} />
</div>
<Button disabled={username.length < 1 || password.length < 1} type="submit" fullWidth size="large" className="mb-4" variant="contained" color="secondary" style={{ textTransform: "none", fontFamily: "'Poppins', sans-serif", fontSize: "1.1rem" }}>Add Note</Button>
</form>
<p>Don't have an account? <Link to="/register" >register</Link> </p>
</div>
</div>
)
}
export default Login
当我试图给出错误的输入时,这个错误发生在handlesubmit函数中,这个输入应该会给我一个错误的响应,但是它给出了以下错误,用户名设置和passwordReset没有被执行,但是当我给出正确的用户名和密码时,我得到了正确的数据
错误:
Uncaught (in promise) Error: Request failed with status code 400
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.onloadend (xhr.js:66)
该路由的后端代码:
router.post('/login', validateUserLogin, catchAsync(loginUser))
module.exports.loginUser = async (req, res) => {
const { username, password } = req.body
const foundUser = await User.findAndValidate(username, password)
if (foundUser) {
const data = {
user: { id: foundUser._id }
}
const authToken = jwt.sign(data, process.env.JWT_KEY)
res.send({ success: true, authToken })
} else {
return res.status(400).json({ success: false, err: { user: foundUser }, message: "invalid credentials !!" })
}
}
当我发送错误的密码用户名时,我没有收到此无效凭据消息
发布于 2021-11-26 10:06:33
发布于 2021-11-26 10:13:17
您没有处理handlesubmit
中的错误
在使用promise时,如果您使用的是await
,请使用try-catch
,或者使用then
和catch
来正确处理promise拒绝。
在您的代码中,如果使用http代码400,axios将拒绝承诺,而您没有在任何地方处理该错误,因此await axios.post(
${HOST}/api/auth/login, data, config);
之后的任何代码都不会运行。
使用try-catch正确处理该错误。
handleSubmit = async (evt) => {
evt.preventDefault();
try {
const config = { headers: { "Content-Type": "application/json" } };
const data = JSON.stringify({ username, password });
console.log(data);
const response = await axios.post(`${HOST}/api/auth/login`, data, config);
console.log(response.data);
resetUsername();
resetPassword();
} catch (err) {
// do something when error occurrs
console.log(err);
}
};
https://stackoverflow.com/questions/70122556
复制相似问题