0
0

More than 3 years have passed since last update.

Lambda で返ってくる文字列でハマった

Last updated at Posted at 2021-03-15

問題

Lambda、API Gateway を使って Web ブラウザからの入力結果を処理していた。Lambda 関数の戻り値に不要なダブルクォーテーションがついていた。

以下のような Lambda 関数を作成した。

lambda_function.py
if bool:
    return 'Exist'
else:
    return 'NotExist'

lambda_function.pyの戻り値がresponse.text()に格納されるのだが、bool が True であるにも関わらず、result === 'Exist' の結果が false になっていた。

main.js
fetch(url, requestOptions)
.then(response => response.text())
.then(result => {
  if (result === 'Exist') {
    alert('存在します。');
  } else {
    alert('存在しません。');
  }
})

ログを見ると、result の値が ""Exist"" となっていた。そこで replace メソッドを使った。

main.js
fetch(url, requestOptions)
.then(response => response.text())
.then(result => {
  if (result.replace(/"/g, '') === 'Exist') {
    alert('存在します。');
  } else {
    alert('存在しません。');
  }
})

replace

'Hello, WORLD!'.replace(/o/ig, '')
// 結果:"Hell, WRLD!"
  • i フラグ:大文字と小文字の違いを無視して置換
  • g フラグ:指定した正規表現にマッチするすべての文字列を置換(グローバルマッチ)

参考記事

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0