LoginSignup
0
0

GASを使おうとしている人へ

クライアント用にwebアプリのデモシステムを、GoogleAppScript + Googleスプレッドシートを使って実装していました。先に言っておくと、ちゃんとしたwebアプリを作るならFastAPIやNodejsのexpress、honoなど得意な言語でvscodeをしばいて作った方がいいです。

理由は主にこうです。

  • REST APIの構築がめんどい
  • エラーハンドリング未対応
  • ログが出力されない
  • post時のjson通信がまじでやばい

Google App Scriptの立ち上げ

今回はSpread SheetをデータベースとしてAPIを組んでみます。
テキトーに無題のスプレッドシートをつくり、拡張機能からリンクできます。
image.png

「概要」をみたときに、コンテナにリンクしたスプシが表示されていればOK
image.png

APIを書いていく

Getメソッド

doGet()とすることで、getメソッドにあたる処理をかけます。

コード.gs
function doGet() {
    return ContentService.createTextOutput("get is ok")
};

return ContentServiceで基本リクエストボディを返すのですが、何をミスったかtextで返すことが前提となっており、jsonを返したい場合は以下のようにする必要があります。

コード.gs
function doGet() {
    let response = JSON.stringify({
    text: "get is ok"
    });
    return ContentService.createTextOutput(response).setMimeType(ContentService.MimeType.JSON)
};

Postメソッド

doPost()とすることで、postメソッドにあたる処理をかけます。

コード.gs
function doPost(request) {
    return ContentService.createTextOutput("post is ok")
};

jsonリクエストを受け取る場合、引数のrequestに対し、以下のようにします。これで通常通りjsonとしてプロパティを参照できます。

コード.gs
function doPost(request) {
    let request_body = JSON.parse(request.postData.getDataAsString());
    let response = JSON.stringify({
    text: request_body.text
    });
    return ContentService.createTextOutput(response).setMimeType(ContentService.MimeType.JSON)
};

デプロイ & fetch

以下のようにしてデプロイしましょう。
SS 2024-06-12 20.45.06.png

URLが公開されるので、postメソッドにfetchしてみます。

fetch.js
fetch("https://script.google.com/macros/s/[デプロイID]/exec",
    {
        method: "POST",
        body: JSON.stringify({text: "post is ok"})
    }
).then(
    (response) => response.json()
).then(
    (data) => {
        console.log(data);
    }
);

ここで、Content-Type: "application/www-form-urlencoded"とかいうheaderをつけないと、受け取れなかったり。CORSのエラーが発生した場合は、mode: no-corsをつけると解決したりします。
ご自身の環境で試してみてください。

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