未处理的拒绝(TypeError):error.response 未定义
2021-01-21
4500
提交表单时出现以下错误
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 | });
这是我的代码:
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;
1个回答
显然 -
error
对象不包含
response
字段。在使用
axios
的上下文中 - 这基本上意味着请求未正确执行(并且服务器根本没有响应)
来自 此 答案:
传统方法是在
catch()
块中捕获错误,如下所示:
axios.get('/api/xyz/abcd')
.catch(function (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);
}
});
Klimenko Kirill
2021-01-22