AWS Lambda(node.js v16)からphpのwebapiにaxiosでpostする

AWS Lambda(node.js v16)からphpのwebapiにaxiosでpostする

Lambdaからphpのwebapiを呼び出す処理があったのですが、少しハマったのでメモです。

具体的にはリクエストボディのJSONデータがphpのwebapiでは空配列になります。

node.jsソースの一部です。

const url = 'https://xxxx.co.jp/hoge.php'
const data = {} // 何かしらのJSONデータ
await axios.post(url, data)

これだとphp側では、$_POSTでは空配列となってしまいます。

file_get_contents(‘php://input’);

$_POSTで受け取らず、file_get_contents(‘php://input’);とすればリクエストボディのJSONを受け取ることが可能です。

ただこれはwebapiであるphpを修正してもよい場合のみ可能な対応です。

URLSearchParams

webapiのphpを修正することができない場合、どうしても$_POSTに値を入れないといけません。

$_POSTはContent-Type:application/jsonに対応していないようなので、URLSearchParamsを使用してContent-type: application/x-www-form-urlencodedで渡します。

ヘッダはContent-Type: application/jsonにせずに未指定のデフォルトでOKです。(Content-type: application/x-www-form-urlencoded)

const url = 'https://xxxx.co.jp/hoge.php'
const data = {} // 何かしらのJSONデータ
const param = new URLSearchParams(data)
await axios.post(url, param)

これで、$_POSTにJSONデータが渡ります。

ネストされたJSONデータを渡す場合はqsモジュールを使用する

ネストされたJSONオブジェクトをPOSTする場合はqsモジュールを使用します。

その際ヘッダはapplication/x-www-form-urlencodedを指定します。※未指定でもOK

import qs from 'qs'

const data = { // ネストされたJSON
  key1:[{
    nestdata:1
  }],
}
const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data: qs.stringify(data),
  url: 'https://xxx.co.jp/hoge.php'
}

ネストされたJSONオブジェクトの場合は、URLSearchParamsよりqsが推奨されているようです。

Note The qs library is preferable if you need to stringify nested objects, as the querystring method has known issues with that use case.

curl

curlコマンドの例です。

$ curl -H "Content-Type: application/x-www-form-urlencoded" \
  https://xxxx.co.jp/hoge.php -d @-<<EOF
name=takahashi&age=20
EOF

参考サイト

【PHP】$_POSTが空になる
とあるAPIでwebhookを使用して通知を受け取り、DBを更新するプログラムを作成していたのですが、何度試してもPOSTデータが受け取れませんでした。プログラムは動いたのでwebhookは動いているようなのですが、$_POSTが空で帰って...
axios not sending request body in nodejs
I'm trying to send a POST request using axios from NodeJS, but the body/data of the request is not sent. I am using axio...
URLSearchParams - Web API | MDN
URLSearchParams インターフェイスは URL のクエリー文字列の操作に役立つメソッドを定義します。
GitHub - axios/axios: Promise based HTTP client for the browser and node.js
Promise based HTTP client for the browser and node.js - GitHub - axios/axios: Promise based HTTP client for the browser ...

コメント

株式会社CONFRAGE ITソリューション事業部をもっと見る

今すぐ購読し、続きを読んで、すべてのアーカイブにアクセスしましょう。

続きを読む

タイトルとURLをコピーしました