When submitting form I get the following following error
Unhandled Rejection (TypeError): error.response is undefined
handleLogin/<
D:/project3.0/containerapp/src/login.js:74
71 | props.history.push('/dashboard');
72 | }).catch(error => {
73 | setLoading(false);
> 74 | if (error.response.status === 401) setError(error.response.data.message);
|^75 | else setError("Something went wrong. Please try again later.");
76 | });
Here is my code:
import React, { useState} from 'react';
import axios from 'axios';
import { setUserSession } from './Utils/Common';
function Login(props) {
const [loading, setLoading] = useState(false);
const username = useFormInput('');
const password = useFormInput('');
const [error, setError] = useState(null);
// handle button click of login form
const handleLogin = () => {
setError(null);
setLoading(true);
axios.post('http://localhost:4000/users/signin', { username: username.value, password: password.value }).then(response => {
setLoading(false);
setUserSession(response.data.token, response.data.user);
props.history.push('/dashboard');
}).catch(error => {
setLoading(false);
if (error.response.status === 401) setError(error.response.data.message);
else setError("Something went wrong. Please try again later.");
});
}
return (
<div>
Login<br /><br />
<div>
Username<br />
<input type="text" {...username} autoComplete="new-password" />
</div>
<div style={{ marginTop: 10 }}>
Password<br />
<input type="password" {...password} autoComplete="new-password" />
</div>
{error && <><small style={{ color: 'red' }}>{error}</small><br /></>}<br />
<input type="button" value={loading ? 'Loading...' : 'Login'} onClick={handleLogin} disabled={loading} /><br />
</div>
);
}
const useFormInput = initialValue => {
const [value, setValue] = useState(initialValue);
const handleChange = e => {
setValue(e.target.value);
}
return {
value,
onChange: handleChange
}
}
export default Login;
question from:
https://stackoverflow.com/questions/65834772/unhandled-rejection-typeerror-error-response-is-undefined 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…