
在 Apigee 环境中使用 JavaScript 脚本处理 JSON 数据时,经常会遇到 TypeError: Cannot set property of undefined 错误。这个错误表明你试图在一个未定义的(undefined)对象上设置属性。 根本原因是访问的JSON对象的某个属性不存在,导致后续操作无法进行。下面我们将通过一个具体的例子来说明如何解决这个问题。
问题分析
假设你有一个 JSON 对象存储在 response.content 变量中,并且你想要向该对象添加一个嵌套的 test 对象,并在 test 对象中设置 case 属性。原始代码如下:
var Backend_Response = JSON.parse(context.getVariable('response.content'));
Backend_Response.test.case = 120;
context.setVariable('response.content',JSON.stringify(Backend_Response));这段代码的问题在于,如果 Backend_Response 对象中不存在 test 属性,那么 Backend_Response.test 将会返回 undefined。此时,你试图在 undefined 上设置 case 属性,就会导致 "TypeError: Cannot set property of undefined" 错误。
立即学习“Java免费学习笔记(深入)”;
解决方案
要解决这个问题,你需要确保在设置 case 属性之前,test 对象已经存在。你可以通过以下方式来创建 test 对象:
var Backend_Response = JSON.parse(context.getVariable('response.content'));
// 检查 test 属性是否存在
if (Backend_Response.test === undefined) {
Backend_Response.test = {}; // 如果不存在,则创建一个空对象
}
Backend_Response.test.case = 120;
context.setVariable('response.content',JSON.stringify(Backend_Response));或者,更简洁的写法是:
var Backend_Response = JSON.parse(context.getVariable('response.content'));
Backend_Response.test = Backend_Response.test || {}; // 如果 test 不存在,则创建一个空对象
Backend_Response.test.case = 120;
context.setVariable('response.content',JSON.stringify(Backend_Response));代码解释
- JSON.parse(context.getVariable('response.content')): 从 Apigee 上下文中获取 response.content 变量的值,并将其解析为 JSON 对象。
- Backend_Response.test = Backend_Response.test || {};: 这是一个短路求值表达式。如果 Backend_Response.test 存在(即不为 undefined、null、false、0 或 ""),则 Backend_Response.test 的值保持不变。如果 Backend_Response.test 不存在,则创建一个新的空对象 {} 并将其赋值给 Backend_Response.test。
- Backend_Response.test.case = 120;: 在 test 对象中设置 case 属性的值为 120。
- context.setVariable('response.content',JSON.stringify(Backend_Response)): 将修改后的 JSON 对象转换为字符串,并将其设置回 Apigee 上下文中的 response.content 变量。
示例
假设 response.content 的初始值为:
{
"Primary": "Status"
}运行修改后的 JavaScript 代码后,response.content 的值将变为:
{
"Primary": "Status",
"test": {
"case": 120
}
}注意事项
- 在处理 JSON 数据时,务必确保要访问的属性存在,或者在使用前先创建它们。
- 使用 typeof 运算符或 === undefined 来检查属性是否存在。
- 使用短路求值表达式 (||) 可以更简洁地创建对象。
- 确保 context.getVariable 获取的变量存在,否则也会导致类似错误。
总结
通过本教程,你学习了如何解决在 Apigee 环境中使用 JavaScript 脚本时遇到的 "TypeError: Cannot set property of undefined" 错误。 关键在于,在设置 JSON 对象的嵌套属性之前,要确保该属性已经存在。 通过检查和创建缺失的属性,可以避免此类错误,并确保 API 代理的稳定运行。 掌握这些技巧,可以让你更加高效地处理 Apigee 中的 JSON 数据。










