node.js - 如何在 Node/Express 的客户端中正确呈现服务器端错误?
问题描述
我已经设置了一个简单的 Node/Express 服务,可以为数据库创建新的书签。
在我的书签架构中,其中一个字段 url 具有验证。当您尝试在没有正确验证的情况下创建新书签时,它会引发错误和消息。
例如,如果您没有为请求提供 url,那么它将抛出一条消息Please provide a url.
POST 请求创建新书签的路径:
app.post(
'/api/bookmarks',
(req, res) => {
const { url, tags } = req.body;
const bookmark = new Bookmark({
url,
tags
});
bookmark.save()
.then(res => {
res.send(result)
})
.catch(error => {
console.log("err:", error);
res.status(400).send(error)
});
}
);
我的书签架构是什么样的:
const bookmarkSchema = new Schema({
url: {
type: String,
required: [true, "Please provide a URL."],
match: [urlRegex, "Your URL is invalid. Please make sure to add www."]
},
tags: [String]
});
当我在前端客户端(例如通过React )上进行 API 调用时,我能够捕捉到错误和后续消息Please provide a URL.
(err.response.data.errors.url.message
axios.post('http://localhost:5000/api/bookmarks', { tags: ["banana", "orange"] })
.then(result => console.log('Result:', result.data))
.catch(err => console.log('Error:', err.response.data.errors.url.message));
我在想什么 - 有没有更好的方法在这里呈现错误?在客户端处理错误会更好吗?
我对错误处理很陌生,所以想知道什么是最佳实践。
谢谢!
解决方案
像这样的东西。所以你不必在模式中检查它。
app.post(
'/api/bookmarks',
(req, res) => {
const { url, tags } = req.body;
if (!url) {
res.status(400).send({error: "URL is missing"})
return;
}
if (!url.match(urlRegex) {
res.status(400).send({error: "URL is not valid"})
return;
}
const bookmark = new Bookmark({
url,
tags
});
bookmark.save()
.then(res => {
res.send(result)
})
.catch(error => {
console.log("err:", error);
res.status(500)
});
}
);
将服务器端错误发送到前端是一种不好的做法。这是一种泄露数据库/后端信息的简单方法。您应该发送自己的字符串消息而不是捕获的错误。
推荐阅读
- android - 如何从 Android 模拟器连接到本地 Python 服务器
- reactjs - useDispatch() 错误:找不到 react-redux 上下文值;请确保组件被包裹在一个
- swift - 具有动态数据的 SwiftUI 分层选取器
- java - 如何在 Mybatis for Postgresql db 中使用 like (NOT IN) 编写查询?
- c# - 通过 WinApi32 监控剪贴板中的变化
- r - 在 R 中使用循环绘制图形
- python - Python(3)类属性怪异
- gpu - Ubuntu - 如何判断 CPU 应用程序当前正在使用 AVX 还是 SSE?
- xml - PL/SQL:循环遍历 XML 列并从重复元素中提取值
- react-native - 5 秒后褪色 React Native 元素