簡體   English   中英

如何使用 React 處理 Node.js API 錯誤

[英]How to handle Node.js API errors with React

我目前正在 Node.js 和 React 客戶端的幫助下開發 RESTful API。

我剛開始,即通過注冊表創建用戶,我意識到我真的不知道如何處理我的 API 用 React 發送給我的錯誤。

例如,如果我想用一個已經被占用的用戶名注冊,我的 API 的控制器將拋出一個錯誤:

throw {status: 422, message: "Username already used"}

我的 React 客戶端現在將檢索它並在控制台中顯示它,但它顯示一個非常普遍的錯誤(請求失敗,狀態代碼 422)而不是消息“用戶名已使用”

_addUser(username, email, password)
 .then((res) => {
   console.log(res);
 })
 .catch((err) => {console.log(err.message)})

有沒有人知道如何解決我的問題? 或者另一種處理錯誤的方法?

嘗試這個:

.catch((err) => {
    console.log(err.response); // err.response.status will give you the error code.
})

您的后端 Node.js 代碼:

return res.status(500).json({message: "Email already registered"})

您的前端 React 或 React Native 代碼:

try{// some code}
catch (error){
   console.log(error.response.data.message)

}

這很晚了,但我想出了為什么沒有顯示您的自定義錯誤。 在您的 catch 塊中,而不是控制台日志記錄:

err.message

嘗試記錄:

err.**response**

在您的控制台中查看並相應顯示:)

您應該使用new關鍵字拋出錯誤。 然后您應該能夠顯示該消息。

throw new Error('Username already used')

或者,如果您使用的是 express,您可以像這樣:

res.status(422).send('Username already used')
Please refer a below link:
https://medium.com/@chiragpatel.cmpicamsit15/error-handling-from-express-js-node-js-to-react-axios-error-handling-7758de90d365

**Server Side Node Js Code :**

   module.exports = (app) => {
app.put(‘/updateUser’, (req, res, next) => {
passport.authenticate(‘jwt’, { session: false }, (err, user, info) => {
if (err) {
console.error(err);
}
if (info !== undefined) {
console.error(info.message);
res.status(403).send(info.message);
} else {
User.findOne({
where: {
username: req.body.username,
},
}).then((userInfo) => {
if (userInfo != null) {
console.log(‘user found in db’);
userInfo
.update({
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
})
.then(() => {
console.log(‘user updated’);
res.status(200).send({ auth: true, message: ‘user updated’ });
});
} else {
console.error(‘no user exists in db to update’);
res.status(401).send(‘no user exists in db to update’);
}
});
}
})(req, res, next);
});
};


**Client-Side (React JS) :**


updateUser = async (e) => {
const accessString = localStorage.getItem(‘JWT’);
if (accessString === null) {
this.setState({
loadingUser: false,
error: true,
});
}
const {
first_name, last_name, email, username
} = this.state;
e.preventDefault();
try {
const response = await axios.put(
‘http://localhost:3003/updateUser’,
{
first_name,
last_name,
email,
username,
},
{
headers: { Authorization: `JWT ${accessString}` },
},
);
// eslint-disable-next-line no-unused-vars
console.log(response.data);
this.setState({
updated: true,
error: false,
});
} catch (error) {
console.log(error.response.data);
this.setState({
loadingUser: false,
error: true,
});
}
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM