我需要呈現我的API給我的錯誤,比如res.status(422).json({ error: error.message }),它帶給我的資訊是密碼驗證。我嘗試使用一些axios工具,但沒有任何作用,比如.catch。你能幫助我嗎?
回復:
function Register() {
const [email, setEmail] = useState(``) 。
const [name, setName] = useState(``/span>)。
const [password, setPassword] = useState(``/span>);
async function onSubmit(event) {
event.preventDefault()。
async function handleSubmit() {
const response = await axios.post("http://localhost:3001/usuario/register"/span>,{
電子郵件。
名字。
密碼。
},{
headers: { "Content-Type"/span>: "application/json" }。
}
);
console.log(response.data)。
const { data } = response;
return data
}
await handleSubmit()。
}
return (
<div>。
...
</div>/span>
)
}
NodeJS:
async adicionaRegistro(infosReg,res) {
const dataCriacao = moment().format("YYY-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({
名稱。
電子郵件。
dataCriacao,
狀態
});
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 }) 。
}
}
uj5u.com熱心網友回復:
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(``/span>)。
const [password, setPassword] = useState(``/span>);
async function onSubmit(event) {
event.preventDefault()。
async function handleSubmit() {
let response;
try {
response = await axios.post(
"http://localhost:3001/usuario/register"。
{
電子郵件。
名字。
密碼。
},
{
headers: { "Content-Type"/span>: "application/json" }。
}
);
} catch (e) {
console.log(e)。
//這里你會看到如果你的后端拋出一個錯誤的結果。
}
if (response) {
console.log( response.data)。
const { data } = response;
return data;
}
}
await handleSubmit()。
}
return <div> 。 ...</div>>。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/309496.html
標籤:
