0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【備忘録】Nuxt + APIGateWay 毎回CORSで引っかかる。対処法

Last updated at Posted at 2020-11-03

エラー

スクリーンショット 2020-11-03 23.16.59.png

よく Nuxtでaxiosを利用するのですが、毎回このエラーで躓きます。

次引っかかった時のためにメモ

APIGatewayを確認する

スクリーンショット 2020-11-04 0.22.01.png

デプロイする

スクリーンショット 2020-11-04 0.22.47.png

Lambdaに追記

 return {
   'statusCode': 200,
   'headers': {
     'Content-Type': 'application/json',  // 追加
     'Access-Control-Allow-Origin': '*'   //追加
   },
   'body': JSON.stringify({ status:’ok’, })
 }

@nuxtjs/proxyを導入

nuxt.config.js

modules: [
    "@nuxtjs/axios",'@nuxtjs/proxy' //追記
  ],

proxy: {
    '/api': {
      target: "APIのURLを入力", // https://xxx-api.ap-northeast1.amazonaws.com/1
      pathRewrite: {
        '^/api' : "ページを開くURLを入力" // https://xxxxxxxxxxx.netlify.app
        }
      },
    },
  

index.vue

async register() {
      const response = await this.$axios.$post(
        "叩きたいAPIURL", // https://xx.ap-northeast-1.amazonaws.com/1/register
        {
          type: "new",
        }
      );
    },


2020/10/17追記

safariとchromeでcorsの処理が異なるらしく、アンドロイドでデバックしていたので気づかなかった。
iphoneやmac safariでエラーが多出し、困った。

特にプリフライトエラーでよくこけた。
これは単純なリクエストで無い場合にoptionリクエストが送られる。
このリクエストでエラーが出ていたために発生したエラーだった。

対処法としては、
スクリーンショット 2020-11-07 20.35.44.png

エンドポイントんいoptionsメゾットを追加し、スクリーンショット 2020-11-07 20.36.13.png

Mockエンドポイントへとつなげた。

他にもいろいろ試してみた方法があったため記述する。

スクリーンショット 2020-11-07 20.37.15.png
スクリーンショット 2020-11-07 20.37.30.png

スクリーンショット 2020-11-07 20.38.07.png

参考文献

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?