creative-account
@creative-account

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

JS+GASで問い合わせフォーム

解決したいこと

昔に似たような質問をしましたが、まだ原因が分からないので再度

JSとGASで問い合わせフォームを作っています。
GitHubPages(もしくはHTMLだけのレンタルサーバー)で公開するのはPHPなどのサーバーサイド言語は使用できません
CORS?というのでエラーが出たので解決方法を教えていただけませんか?

参考【注意】偽サイト作るのちょろすぎて草

発生している問題・エラー

クロスオリジン要求をブロックしました: 同一生成元ポリシーにより、  
https://script.google.com/macros/s/xxxxx/exec?q=aaaa  
にあるリモートリソースの読み込みは拒否されます  
(理由: CORS ヘッダー ‘Access-Control-Allow-Origin’ が足りない)。ステータスコード: 302

クロスオリジン要求をブロックしました: 同一生成元ポリシーにより、https://script.google.com/macros/s/xxxx/exec?q=aaaa  
にあるリモートリソースの読み込みは拒否されます  
(理由: CORS 要求が成功しなかった)。ステータスコード: (null)

Error: TypeError: NetworkError when attempting to fetch resource. index.html:102:17
    submitMessage http://127.0.0.1:3000/index.html:102
    (非同期: promise callback)
    submitMessage http://127.0.0.1:3000/index.html:101
    onclick http://127.0.0.1:3000/index.html:1

該当するソースコード

index.html
      <section class="section">
        <div class="container">
          <textarea name="" class="textarea message" id="" placeholder="Hello world" rows="10"></textarea>
          <div class="field is-grouped">
            <div class="control">
              <button class="button is-link" onclick="submitMessage()">Submit</button>
            </div>
            <div class="control">
              <button class="button is-link is-light">Cancel</button>
            </div>
          </div>
        </div>
      </section>


      <script>
        function submitMessage() {
        const message = document.querySelector('.message').value;
        const encodedMessage = encodeURIComponent(message);
        
        fetch('https://script.google.com/macros/s/xxxxx/exec?q=' + encodedMessage, {
        method: 'GET',
        mode: 'cors' // CORSモードを指定
        })
        .then(response => response.text())
        .then(data => {
        console.log(data);
        })
        .catch(error => {
        console.error('Error:', error);
        });
        }
      </script>
コード.gs
function doGet(e) {
  const spreadSheetByActive = SpreadsheetApp.getActive();
  const sheet = spreadSheetByActive.getActiveSheet();
  sheet.appendRow([e.parameter.q])
  let output = ContentService.createTextOutput();
  output.setMimeType(ContentService.MimeType.JSON);
  output.setContent(e.parameter.q);
  return ContentService.createTextOutput(output);
}

自分で試したこと

ChatGPTに教えてもらってもちゃんと動くコードはできませんでした。
自分の力ではそれで精一杯です。

0

2Answer

表示されているJavascriptとGoogle Apps Scriptを下記のように修正して再度テストしてみてください。

Javascript

function submitMessage() {
  const message = document.querySelector('.message').value;
  const encodedMessage = encodeURIComponent(message);
  fetch('https://script.google.com/macros/s/xxxxx/exec?q=' + encodedMessage)
    .then(response => response.text())
    .then(data => {
      console.log(data);
    })
    .catch(error => {
      console.error('Error:', error);
    });
}

Google Apps Script

function doGet(e) {
  const spreadSheetByActive = SpreadsheetApp.getActive();
  const sheet = spreadSheetByActive.getActiveSheet();
  sheet.appendRow([e.parameter.q]);
  return ContentService.createTextOutput(e.parameter.q);
}
  • Web Appsを使用していると思われますので、スクリプトを修正した後は、最新のスクリプトをWeb Appsへ反映させた後にテストを行ってください。最新のスクリプトを反映させない場合は、修正したスクリプトが正しく動作しませんのでご注意ください。

  • また、今の場合、Web Appsの設定は下記のように行っていることを前提としています。

    • Execute as: Me
    • Who has access to the app: Anyone
1Like

Comments

  1. 試してみましたが、同じエラーでうまくいきませんでした。
    GAS側の設定はこうです
    image.png
    あとWebAppsが何かはわかりませんが使っていません
    検証はVSCodeのLiveServerです。

  2. ご質問にはWeb Appsの設定は含まれておりませんでしたが、コメントから、私の想定した設定とは異なっているようです。表示されているJavascriptの場合、下記の設定で行う必要があります。

    • Execute as: Me
    • Who has access to the app: Anyone

    もしもコメントにあるセッティングで行いたい場合は、Google Apps Script projectをユーザと共有した上でユーザ自身のアクセストークンを使ってリクエストをする必要があります。

    参考

  3. 10ヶ月程返信が遅れてしまい申し訳ありません。
    けっこう設定をいじってみたのですが上手くいかず放置していました。
    最近、JSだけでデータを送信しなきゃいけないプログラムを組むことになったので、もう1度アドバイスを元にやってみたら上手く行きました。本当にありがとうございます。

コードをtanaike氏の提示したものに直した上で、GAS側のWebアプリのデプロイ時の設定を下記のように修正して再デプロイしてみてください。

(この操作によりデプロイurlが新しくなるので、バージョンを付け替えて現在と同じデプロイurlになるようにするか、または呼び出し側(html側)のurlを新しいデプロイurlに変えてください)
image.png

1Like

Comments

  1. 10ヶ月程返信が遅れてしまい申し訳ありません。
    けっこう設定をいじってみたのですが上手くいかず放置していました。
    最近、JSだけでデータを送信しなきゃいけないプログラムを組むことになったので、もう1度アドバイスを元にやってみたら上手く行きました。本当にありがとうございます。

Your answer might help someone💌