17
11

More than 5 years have passed since last update.

axios で、パラメーターを form-data として送信してAPI Gatewayに飛ばす

Last updated at Posted at 2017-05-14

かなりはまってしまった。

問題

モダンなJSのhttpリクエストでおなじみのaxiossuperagentは、
データ送信の際にパラメーターを「Payload」というものに入れて送信している。

そっちの方が効率が良いのだそう。

これを利用して、axiosから AWS の API Gateway に送信しようとして、はまった。

API Gatewayでは、bodyにJsonを入れる形式、つまり

curl -H 'Content-Type: application/x-www-form-urlencoded' \
--data '{"name": "kazuya", "email": "kazuya@kazuya.com"}`' API_ENDPOINT

などとして送信しないとエラーになってしまうためだ。

解決策

axios でこれを実現するには、単純にこれで良い。

axios.post(API_ENDPOINT, JSON.stringify({
  name: 'kazuya',
  email: 'kazuya@kazuya.com'
}))

二個目の引数に文字列を入れてあげれば勝手になったのか・・・・
下記のStack Overflowで知った。

17
11
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
17
11