Express - 补丁请求验证
Express - Validation for Patch Requests
我是一名前端开发人员,正在尝试使用 Node/Express.
为我的项目创建其余部分 api
我正在使用 Joi
进行验证。我很好奇如何 PATCH
请求路线。我不能使用 Joi
因为它说 this field is required
.
所以我想知道如何验证 PATCH
请求路由。因为我不知道我会得到什么数据。未经验证使用 req.body
会出现什么问题?
export const updateAccount = asyncHandler(async (req, res) => {
let values = req.body;
if (req.method === 'PUT') {
values = await accountSchema.validateAsync(req.body);
}
const account = await Account.findByIdAndUpdate(req.params.id, values, {
new: true,
});
if (!account) {
return res.status(404).json({ message: 'Account not found' });
}
res.status(200).json(account);
});
正如@aliland 所提到的,也遵循永远不要相信用户输入。我已经为补丁请求创建了一个新的 Joi
模式。因为在当前模式下它抱怨必填字段。
我的架构:
const accountSchemaForPatchRequests = Joi.object({
firstName: Joi.string().min(3).max(30),
lastName: Joi.string(),
email: Joi.string().email(),
password: Joi.string().min(8),
});
和控制器:
export const updateAccount = asyncHandler(async (req, res) => {
let values = req.body;
if (req.method === 'PUT') {
values = await accountSchema.validateAsync(req.body);
} else {
values = await accountSchemaForPatchRequests.validateAsync(req.body);
}
const account = await Account.findByIdAndUpdate(req.params.id, values, {
new: true,
});
if (!account) {
return res.status(404).json({ message: 'Account not found' });
}
res.status(200).json(account);
});
我是一名前端开发人员,正在尝试使用 Node/Express.
为我的项目创建其余部分 api我正在使用 Joi
进行验证。我很好奇如何 PATCH
请求路线。我不能使用 Joi
因为它说 this field is required
.
所以我想知道如何验证 PATCH
请求路由。因为我不知道我会得到什么数据。未经验证使用 req.body
会出现什么问题?
export const updateAccount = asyncHandler(async (req, res) => {
let values = req.body;
if (req.method === 'PUT') {
values = await accountSchema.validateAsync(req.body);
}
const account = await Account.findByIdAndUpdate(req.params.id, values, {
new: true,
});
if (!account) {
return res.status(404).json({ message: 'Account not found' });
}
res.status(200).json(account);
});
正如@aliland 所提到的,也遵循永远不要相信用户输入。我已经为补丁请求创建了一个新的 Joi
模式。因为在当前模式下它抱怨必填字段。
我的架构:
const accountSchemaForPatchRequests = Joi.object({
firstName: Joi.string().min(3).max(30),
lastName: Joi.string(),
email: Joi.string().email(),
password: Joi.string().min(8),
});
和控制器:
export const updateAccount = asyncHandler(async (req, res) => {
let values = req.body;
if (req.method === 'PUT') {
values = await accountSchema.validateAsync(req.body);
} else {
values = await accountSchemaForPatchRequests.validateAsync(req.body);
}
const account = await Account.findByIdAndUpdate(req.params.id, values, {
new: true,
});
if (!account) {
return res.status(404).json({ message: 'Account not found' });
}
res.status(200).json(account);
});