LoginSignup
21
11

More than 3 years have passed since last update.

GAS(自作API) ✕ Nuxt で CORSエラーで詰みかけた話

Last updated at Posted at 2020-06-05

この記事で分かること

  • GASで自作APIを叩いた時のCORSエラーの解決方法

悪夢の始まり

自分のポートフォリオサイトを作成していたときのこと・・・

お問合せフォームから、Axiosで自作のGASのAPIを叩いた時に、おなじみのCORSエラー、クロスオリジン問題が起きてしまった。

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, 
set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

CORSエラーってなんぞや?という方は、こちらの記事に分かりやすくまとまっているので、確認してみると良いでしょう。
なんとなく CORS がわかる...はもう終わりにする。

GASはレスポンスヘッダーの OPTION をサポートしていない。。

通常、自作APIでCORSエラーが出た時は、サーバーサイド(今回で言えばGAS側)のレスポンスヘッダーに以下の OPTION をつければ解決するはずなのだ。

Access-Control-Allow-Origin: {{アクセスする側のURL}}

しかし! 残念ながらGASはどうやら OPTION をサポートしていないらしい。
詳しくは 今から10分ではじめる Google Apps Script(GAS) で Web API公開

じゃあどうするんだ。。

解決方法

当初、GAS側のコードでは doPost 関数を使用してPOSTでのデータの受け渡しを想定していた。

どうやら、GASのコードを doPost から doGet に変更して、Axios のパラメータに crossDomain: true を追加してあげると改善される。

POSTでは上手く行かないらしい。。

実際に書いたコードは下の通りになった。

index.vue
const params = {
        //任意のパラメータ
        crossDomain: true
      }
const { data } = await axios.get(process.env.GAS_URL, { params })
return data
main.gs
function doGet(e) {
  const params = e.parameter
  const example = params.example;  // => exampleが取れる

  //任意の処理

  const output = ContentService.createTextOutput();
  output.setMimeType(ContentService.MimeType.JSON);
  output.setContent(JSON.stringify({"message":"success"}));

  return output;
}
21
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
21
11