如何在JSON请求含无效属性时抛出错误?(Node.js接口优化需求)
实现请求体属性校验的Node.js接口修改方案
我们需要修改editarRolInstitucional接口,确保请求体仅包含"nombre"属性,若存在其他额外属性则返回错误。当前代码仅校验了"nombre"的存在,缺少多余属性的校验逻辑,以下是完整的修改实现:
export const editarRolInstitucional = async (req: Request, res: Response) => { try { const {id} = req.params; const bodyKeys = Object.keys(req.body); // 校验请求体仅含"nombre"属性,且该属性有值 if(bodyKeys.length === 1 && bodyKeys[0] === 'nombre' && req.body.nombre){ const rolInstitucional = await RolInstitucional.findByPk(id); if(rolInstitucional) { await rolInstitucional.update({nombre: req.body.nombre}); res.status(200).json({ message: 'El rol institucional ha sido editado con éxito', data: rolInstitucional }); } else { res.status(400).json({ message: 'El rol institucional no existe en la base de datos' }) } } else { // 根据不同错误场景返回对应提示 if(bodyKeys.length !== 1 || !bodyKeys.includes('nombre')){ res.status(400).json({ message: '请求体仅允许包含"nombre"属性' }); } else { res.status(400).json({ message: 'El campo a editar no es válido' }); } } } catch (e) { res.status(400).json({ message: 'Error al editar el rol institucional', error: e }); }
关键校验逻辑说明
- 获取请求体属性集合:通过
Object.keys(req.body)提取请求体中所有属性的名称,形成数组用于校验 - 严格属性合法性判断:同时满足三个条件:属性数量为1、唯一属性是"nombre"、"nombre"字段有有效值,才进入后续业务流程
- 精准错误提示:在校验不通过时,区分「存在多余属性/缺少必要属性」和「"nombre"字段无效」两种场景,返回对应提示信息
- 保留原有业务逻辑:校验通过后,维持原有的数据库查询、更新和响应逻辑不变
内容的提问来源于stack exchange,提问作者Felipe Antonio Guzmán Anabalon
相关产品推荐
相关产品推荐

