2017-08-29 38 views
0

我正在使用AWS lambda + API網關,並且需要在URL(GET方法)中爲REST調用傳遞一個數字數組。看起來好的方法是將數字作爲字符串(逗號分隔)傳遞,然後使用JSON.parse轉換爲數組數組。JSON.parse()中的錯誤(當從API網關中調用時)

以下是我使用的AWS lambda代碼;

exports.handler = (event, context, callback) => { 

    var arr = JSON.parse('[' + event.numbers + ']'); 
    console.log("array: " + arr); 

    // TODO implement 
    callback(null, 'Hello from Lambda'); 
}; 

我使用此Input輸入測試事件在AWS Lambda中測試此函數;

{ 
    "numbers": "1,5" 
} 

而且一切都按預期工作;沒有錯誤。但是,當我通過API網關測試它,並在查詢中傳遞數字作爲字符串時,我得到以下錯誤(通過CloudWatch觀察);

*19:19:02 
START RequestId: eabab882-8cee-11e7-8e2f-79d3086e061f Version: $LATEST 
19:19:02 
2017-08-29T19:19:02.688Z eabab882-8cee-11e7-8e2f-79d3086e061f SyntaxError: Unexpected token u in JSON at position 1 at Object.parse (native) at exports.handler (/var/task/index.js:4:20) 
19:19:02 
END RequestId: eabab882-8cee-11e7-8e2f-79d3086e061f 
19:19:02 
REPORT RequestId: eabab882-8cee-11e7-8e2f-79d3086e061f Duration: 215.25 ms Billed Duration: 300 ms Memory Size: 128 MB Max Memory Used: 18 MB 
19:19:02 
RequestId: eabab882-8cee-11e7-8e2f-79d3086e061f Process exited before completing request* 

這是傳遞給lambda的請求,如日誌所示;

"body-json" : {}, 
"params" : { 
"path" : { 
    } 
    ,"querystring" : { 
     "numbers" : "1,6" 
      } 
    ,"header" : { 
    } 
    }, 
"stage-variables" : { 
}, 

我找不出什麼問題,因爲我在兩種情況下都傳遞了相同的字符串。

我將不勝感激任何幫助。

感謝 格斯

回答

相關問題