実現したいこと
こちらの流れにおいて (3) を実現したいです。
(1) GAS に NotionAPI でのページ作成処理を実装 → 実現できた
(2) その GAS を, 任意のサイトのフロントから fetch()
で実行 → 実現できた
(3) 任意のサイトで GAS の返り値 ( NotionAPI の返り値 ) を確認 → これを実現したい
発生している問題・エラーメッセージ
任意のサイト ( https://example.com ) のコンソールでこちらの fetch()
を実行すると、GAS は処理されて Notion に無事ページは作成されました。つまり (1) (2) はできたのです。( 実際はコンソールで実行するのではなくChrome拡張機能で「実行」ボタンを作ります。)
JavaScript
1const gasEndpointUrl = 'https://script.google.com/macros/s/●●●/exec'; 2 3fetch(gasEndpointUrl) 4 .then(response => response.text()) 5 .then(data => { 6 console.log(data); 7 }) 8 .catch(error => { 9 console.error('Error:', error); 10 });
しかし、任意のサイトのコンソールにこちらのエラーメッセージが表示され、(3) ができない状況です。
Access to fetch at 'https://script.google.com/macros/s/●●●/exec' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
該当のソースコード
こちらが GAS のコードです。async
で NotionAPI の返り値を待って return
しています。
Notion に無事ページは作成されましたし、35行目の console.log()
も正常な NotionAPI の返り値でした。
JavaScript
1/*============================================== 2 3 NotionAPIでページを作成 4 - Notion に無事ページは作成されました 5 - 35行目の console.log() も正常な値でした 6 7==============================================*/ 8 9// NotionAPIキー 10const TOKEN = 'secret_▲▲▲'; 11 12// GASの実行 13async function doGet() 14{ 15 const mainResult = await main(); 16 return ContentService.createTextOutput(JSON.stringify(mainResult)); 17} 18 19/** 20 * メイン処理 21 */ 22async function main(){ 23 try { 24 25 // ページ作成 26 const databaseId = '■■■'; 27 const fetchedContent = await createPage(databaseId); 28 29 // Notion側でエラー 30 if (fetchedContent.object === 'error') { 31 throw ('Notion側でエラー'); 32 } 33 34 // 結果確認 35 console.log('fetchedContent: ', fetchedContent); 36 return fetchedContent; 37 38 } catch(e) { 39 console.log('e: ', e); 40 return e; 41 } 42} 43 44/** 45 * ページ作成 46 * マニュアル https://developers.notion.com/reference/post-page 47 */ 48async function createPage(databaseId) 49{ 50 const payload = { 51 "parent": { 52 "database_id": databaseId 53 }, 54 "properties": { 55 "Name": { 56 "title": [ 57 { 58 "text": { 59 "content": getCurrentDate() 60 } 61 } 62 ] 63 }, 64 } 65 }; 66 67 const options = { 68 'method': 'POST', 69 'headers': { 70 'content-type': 'application/json; charset=UTF-8', 71 'Authorization': 'Bearer ' + TOKEN, 72 'Notion-Version': '2022-06-28' 73 }, 74 'muteHttpExceptions': true, 75 'payload': JSON.stringify(payload) 76 } 77 const endpoint = 'https://api.notion.com/v1/pages'; 78 const fetchedContent = fetchUrl(endpoint, options, 'json'); 79 return fetchedContent; 80} 81 82/** 83 * fetch() を実行し getContentText() を返す 84 */ 85async function fetchUrl(url, options = {}, type = 'text') 86{ 87 return new Promise((resolve, reject) => { 88 const response = UrlFetchApp.fetch(url, options); 89 if (response.getResponseCode() === 200) { 90 const content = response.getContentText(); 91 resolve(type === 'json' ? JSON.parse(content) : content); 92 } else { 93 const mes = `Request failed with status code ${response.getResponseCode()}`; 94 reject(new Error(mes)); 95 } 96 }); 97} 98 99/** 100 * 現在日時を 2023-01-01 0:00 の形式で生成 101 * Notionに作成するページのタイトルに使う 102 */ 103function getCurrentDate() 104{ 105 const formatNumber = (number) => (number < 10 ? '0' + number : number); 106 107 const now = new Date(); 108 const year = now.getFullYear(); 109 const month = formatNumber(now.getMonth() + 1); 110 const day = formatNumber(now.getDate()); 111 const hours = formatNumber(now.getHours()); 112 const minutes = formatNumber(now.getMinutes()); 113 114 const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}`; 115 return formattedDateTime; 116}
試したこと [1]
fetch()
の第二引数で'Content-Type'
を以下のように指定しても、全く同じエラーメッセージでした。尚、Notion の方は上記と同様に無事ページは作成されました。
JavaScript
1const gasEndpointUrl = 'https://script.google.com/macros/s/●●●/exec'; 2 3fetch(gasEndpointUrl, { 4 method: 'GET', 5 headers: { 6 'Content-Type': 'application/x-www-form-urlencoded', 7 }, 8 }) 9 .then(response => response.text()) 10 .then(data => { 11 console.log(data); 12 }) 13 .catch(error => { 14 console.error('Error:', error); 15 });
試したこと [2]
また(これはエラーメッセージの CORS の件と関係ないかもしれませんが)、デプロイしたウェブアプリのURL 'https://script.google.com/macros/s/●●●/exec'
に直接ブラウザアクセス ( ブラウザのURLバーに入力 ) すると、'スクリプトが完了しましたが、返された値はサポートされている戻り値の型ではありませんでした。'
と表示されてしまい、NotionAPI の結果を確認することはできませんでした。
試したこと [3]
最後に、該当のソースコードから非同期処理を削除 ( async
とawait
を削除 ) しデプロイしましたところ、上記のエラーメッセージはなくなりました。
しかし、fetch()
の方もブラウザアクセスの方も、いずれも {}
のみを得てしまいました。
ちなみにこの場合も Notion の方は上記と同様に無事ページは作成されました。
試したこと [まとめ]
・非同期処理があると上記 CORS のエラーメッセージが出る。
・非同期処理をやめるとエラーメッセージはなくなるが、非同期でないためにNotionAPIからの返り値の確認という (3) ができない。
・いずれにせよ Notion に無事ページは作成される。
こんな現状です。
補足情報(FW/ツールのバージョンなど)
バージョンなど特筆すべき補足は特にございませんが、質問内容に不足情報などあればご指摘頂ければ幸いです。
直接的な正解に限らず、上記の他に試すべきこと等ございましたら、ぜひご回答宜しくお願い致します。

回答1件
あなたの回答
tips
プレビュー