Skip to content

Instantly share code, notes, and snippets.

@TwoSquirrels
Last active December 29, 2022 14:38
Show Gist options
  • Select an option

  • Save TwoSquirrels/6fff214d4b8ae6ca1420d72b529ce1c5 to your computer and use it in GitHub Desktop.

Select an option

Save TwoSquirrels/6fff214d4b8ae6ca1420d72b529ce1c5 to your computer and use it in GitHub Desktop.
GASでのAPI
/* server.gs */
function doPost(req) { // req.parameterでクエリが手に入るぞ!
// request (reqBodyにリクエストデータが入ってくるぞ!ただしXMLも受け取りたいときは場合分けが必要だから注意な!あ、doGetの時はこれ要らんからな。)
let reqBody;
try {
reqBody = JSON.parse(req.postData.getDataAsString());
} catch(e) {
return ContentService.createTextOutput(
JSON.stringify({
error: {
code: 400,
type: "request body problem",
name: e.name,
message: e.message,
}
})
).setMimeType(ContentService.MimeType.JSON);
}
// response
try {
const resBody = {}; // 返したいオブジェクトをresBodyに入れるのだ!別で関数用意してもいいかも。
return ContentService.createTextOutput(
JSON.stringify(resBody)
).setMimeType(ContentService.MimeType.JSON);
} catch(e) {
// エラーログを吐く処理をここでしよう (メールでエラー送るでもなんでも)
return ContentService.createTextOutput(
JSON.stringify({
error: {
code: 500,
type: "server programm problem",
name: e.name,
message: e.message,
}
})
).setMimeType(ContentService.MimeType.JSON);
}
}
/* script.js */
const request = async (url, method = "GET", reqBody = {}) => {
const options = {
"method": method,
"headers": {
//"Content-Type": "application/json"
// CORS制限回避
"Content-Type": "text/plain"
},
"cache": "no-store",
};
if (method.upperCase() !== "GET") options["body"] = JSON.stringify(reqBody);
const res = JSON.parse(await fetch(url, options).then(res => res.text()));
if (res.error) throw new res.error;
return res;
};
@TwoSquirrels

Copy link
Copy Markdown
Author

@TwoSquirrels

Copy link
Copy Markdown
Author

もともとCORS制限はセキュリティ上の理由で大体のブラウザに付いてるんだけど、
基本的にXSS対策としてあるだけらしいので
別にXSSの心配のない問い合わせフォームなら
ゴリ押しで回避しちゃって大丈夫(たぶんね)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment