node.js - 如何在 reactJS + axios + nodeJS 中呈现 API 错误响应?
问题描述
我需要呈现我的 API 给我的错误,比如res.status(422).json({ error: error.message }),它给我带来的信息是密码验证。我尝试使用一些 axios 工具,但没有任何效果,比如 .catch。你能帮助我吗?
反应:
function Register() {
const [email, setEmail] = useState(``);
const [name, setName] = useState(``);
const [password, setPassword] = useState(``);
async function onSubmit(event) {
event.preventDefault();
async function handleSubmit() {
const response = await axios.post("http://localhost:3001/usuario/register",{
email,
name,
password,
},{
headers: { "Content-Type": "application/json" },
}
);
console.log(response.data);
const { data } = response;
return data
}
await handleSubmit();
}
return (
<div>
...
</div>
)
}
节点JS:
async adicionaRegistro(infosReg, res) {
const dataCriacao = moment().format("YYYY-MM-DD h:mm:ss");
const status = 1;
const name = infosReg.name;
const email = infosReg.email;
const password = infosReg.password;
try {
const usuario = new Usuario({
name,
email,
dataCriacao,
status
});
res.status(201).json();
} catch (erro) {
if (erro instanceof InvalidArgumentError) {
console.log(erro)
res.status(422).json({ erro: erro.message });
} else if (erro instanceof InternalServerError) {
res.status(500).json({ erro: erro.message });
} else {
res.status(500).json({ erro: erro.message });
}
}
}
解决方案
如何try...catch
捕捉错误?https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
function Register() {
const [email, setEmail] = useState(``);
const [name, setName] = useState(``);
const [password, setPassword] = useState(``);
async function onSubmit(event) {
event.preventDefault();
async function handleSubmit() {
let response;
try {
response = await axios.post(
"http://localhost:3001/usuario/register",
{
email,
name,
password,
},
{
headers: { "Content-Type": "application/json" },
}
);
} catch (e) {
console.log(e);
// here you will see the result if your backend is throwing an error
}
if (response) {
console.log(response.data);
const { data } = response;
return data;
}
}
await handleSubmit();
}
return <div>...</div>;
}
推荐阅读
- froala - Froala 编辑器在粘贴到 word 时添加边框
- reactjs - 将 React 组件注入 Chrome 扩展
- python-3.x - 单击 Toast 通知时重定向到特定的 Discord 频道
- sensenet - Sensenet 移动服务器
- database - 访问 WPF 组合框中对象的名称
- java - Java - 通用的工厂类
- python - 使用 sed / awk / bash 将缺失的行号填充到文件中
- ios - 如何在 SwiftUI 中启动应用程序时有条件地加载视图?
- pandas - 如何根据条件行值对 pandas 数据框进行取消堆叠或取消透视?
- mysql - 用于返回没有活动组成员身份的用户的 SQL 查询