问题描述
当我运行这个本地调用时,在我的 NodeJS lambda 中,有效负载以 object
而不是 string
serverless invoke local -f MyfunctionName --data '{ "data": "hello world" }'
这是有原因的吗?如何将此 json 负载作为字符串传递?
解决方法
问题的根源
运行时将三个参数传递给处理程序方法。第一个参数是事件对象,它包含来自调用者的信息。调用程序在调用 Invoke 时将此信息作为 JSON 格式的字符串传递,并且运行时将其转换为对象。当 AWS 服务调用您的函数时,事件结构因服务而异。
由于处理程序期望事件是一个“JSON 格式的字符串”,那么这个字符串将被转换为一个对象是正常的。
如何轻松解决此问题?
与其传递原始 JSON 并期望将其解析为字符串,不如将其包装到 JSON 字段之一中,例如:
serverless invoke local -f MyfunctionName --data '{"inputJson": "{ \"data\": \"hello world\" }"}'
对于这个输入和这个处理程序:
export const handler = async (event,context) => {
console.log('type of event.inputJson = ' + typeof event.inputJson)
console.log('value of event.inputJson = ' + event.inputJson)
const parsedInputJson = JSON.parse(event.inputJson)
console.log('value of inputJson.data = ' + parsedInputJson.data)
};
我收到以下输出:
type of event.inputJson = string
value of event.inputJson = { "data": "hello world" }
value of inputJson.data = hello world