LoginSignup
3
2

More than 1 year has passed since last update.

Amplify×Nuxt.jsで外部APIにPOSTしようとしたらハマった話

Posted at

背景

Nuxt.jsをAmplify CLIでデプロイして外部オリジンのAPIをPOSTしようとしていた。
amplify cliでのデプロイにはManaged Hosting(amplifyhosting)を採用していた。
image.png

また、CORS対策のために、以下のようにproxy設定をしていて、ローカルでは問題なく動いていた。

nuxt.config.js
const backendBaseUrl = process.env.BACKEND_BASE_URL || 'http://localhost:3003'

export default {
  ...
  axios: {
    baseURL: backendBaseUrl,
    proxy: true,
    prefix: '/api',
    credentials: true,
  },
  proxy: {
    '/api/': {
      target: backendBaseUrl,
      pathRewrite: { '^/api/': '' },
      changeOrigin: true,
    }
  },
  ...
}

現象

proxy経由で外部APIに対してPOSTを叩くと、status code 405(MethodNotAllowed)のエラーが発生した
image.png

どうやらcloudfrontがPOSTを拒否しているみたい

解決策

自分の場合は、特定のパスに対して、書き換えてリダイレクトすることでPOSTが成功した

[
    {
        "source": "/api/<*>",
        "target": "(Your API URL)/<*>",
        "status": "200",
        "condition": null
    }
]

こちらの設定はAmplify consoleの「書き換えて、リダイレクト」から設定することができる

「編集」を押す
image.png
「テキストエディタを開く」を押す
image.png
ここでsourceとtargetを設定してあげる

保存してからPOSTを叩き直すと成功した

参考

3
2
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
3
2