简体   繁体   English

如何使用 React 处理 Node.js API 错误

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

I am currently developing a RESTful API with the help of Node.js and a client with React.我目前正在 Node.js 和 React 客户端的帮助下开发 RESTful API。

I am at the very beginning, ie the creation of a user via a registration form, and I realized that I do not really know how to handle the errors that my API sends me with React.我刚开始,即通过注册表创建用户,我意识到我真的不知道如何处理我的 API 用 React 发送给我的错误。

For example if I want to register with a username that is already taken, the controller of my API will throw an error :例如,如果我想用一个已经被占用的用户名注册,我的 API 的控制器将抛出一个错误:

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

My React client will retrieve it and display it in the console at the moment, but it displays a very general error (Request failed with status code 422) and not the message "Username already used"我的 React 客户端现在将检索它并在控制台中显示它,但它显示一个非常普遍的错误(请求失败,状态代码 422)而不是消息“用户名已使用”

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

Does anyone have an idea of ​​how to solve my problem?有没有人知道如何解决我的问题? Or another way to handle errors?或者另一种处理错误的方法?

Try this:尝试这个:

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

Your Backend Node.js code:您的后端 Node.js 代码:

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

Your Frontend React or React Native code:您的前端 React 或 React Native 代码:

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

} }

This is late, but I figured out why your custom error isn't showing.这很晚了,但我想出了为什么没有显示您的自定义错误。 In your catch block, instead of console logging:在您的 catch 块中,而不是控制台日志记录:

err.message

Try logging:尝试记录:

err.**response**

Look at this in your console and display accordingly :)在您的控制台中查看并相应显示:)

You should throw error with the new keyword.您应该使用new关键字抛出错误。 Then you should be able to display the message.然后您应该能够显示该消息。

throw new Error('Username already used')

Or if you are using express, you can go like this:或者,如果您使用的是 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