【发布时间】:2019-03-09 09:58:51
【问题描述】:
我正在使用 NodeJS 和 Express 开发一个 RESTful API。
我注意到传入的请求有时缺少一些预期的变量,这会导致程序崩溃,说它无法将变量的值设置为 'undefined' 值 - 因为请求没有到达值。
示例:
应用程序需要 variableY,但正在发送 variableX:
formData: { variableX: 'valueX' }
程序期望接收变量Y,代码如下:
const checkVariables = Joi.validate({
variableY: req.body.variableY,
}, schema);
应用程序崩溃并出现以下错误:
TypeError: Cannot read property 'variableY' of undefined
我想了一些方法来处理这个问题,包括在应用程序启动时声明变量并一起使用它们,使用try-catch。
另一种方法是使用if-else、if-chaining 或case-switch,但正如你所理解的,我当然正在寻找实现这一目标的最干净的方法。
有什么想法吗?
谢谢。
** 编辑 **
仅使用对象取得进展并设法实现结果。一旦试图到达它的任何内部字段,无论如何都会抛出错误,例如:if(req.body.variableY == undefined){console.log('The expected variable is undefined');} //true
当验证处理“未定义”对象内的字段时:if(req.body.variableY.dataId == undefined){console.log('The expected variable is undefined');} //crashes
再次抛出以下错误:TypeError: Cannot read property 'variableX' of undefined
在做了更多的挖掘之后,找到了这个 Stackoverflow 线程:
How to check if object property exists with a variable holding the property name?
尝试使用 hasOwnProperty,但抛出相同类型的错误:TypeError: Cannot read property 'hasOwnProperty' of undefined
尝试使用try-catch 包装变量声明,仍然没有用:
try{
var variableX = req.body.variableX
var variableXDataId = req.body.variableX.dataId
}
catch(e){
res.status(400).send('Wrong request error: Please check your request variables and try again');
}
因为这是一个非常基本的验证,应该由大多数 RESTful API 解决(验证您在请求中获得了预期的传入变量,因此程序不会因出现无法处理的错误而崩溃 - 什么此类问题(预期/意外请求验证)的常见解决方案是什么?
谢谢。
【问题讨论】:
标签: node.js express request undefined req