お世話になっております。
現在shopifyでアプリ開発をしているのですがcorsエラーで作業が止まっており解決方法をご教授頂きたいです。
現在fetchを使用してストア上にDBからデータを取得して一覧を取得しています。
しかし、ストアからデータを登録する際にfetchを使用して登録のリクエストを送ってもcorsエラーになってしまっています。
現在web/index.js
const allowed_origins = [
`https://${process.env.SHOP}`,
"http://127.0.0.1:9292",
"https://{my-shop}.myshopify.com"
];
app.get("/api/getdata", async (req, res) => {
const origin = String(req.header("origin"));
if (allowed_origins.includes(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Credentials", "true");
}
const data = await prisma.datas.findMany({
// 省略
});
return res.json(data);
});
app.post("/api/datapost", async (req, res) => {
const post_data = req.body;
const origin = String(req.header("origin"));
if (allowed_origins.includes(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Credentials", "true");
}
const new_datas = await prisma.datas.create({
// 省略
});
return res.json(new_datas);
});
corsエラーを回避するためにallowed_originsを作成し、ローカルの開発環境のurlと環境変数から取得したurlを設定しています。検証のため3つ目に直接アプリをインストールしたストアのurlも入れております。
get,postどちらも別のドメインからのfetchのためifを使用しrequestHeaderのoriginがallowed_originsにある場合はres.setHeaderを付与するように記述しております。if文はローカルでの開発中問題なく動作しており、デプロイ後もgetで動作しているため問題ないと思っております。
theme-app-extensions/assets/front.js
async function postData(postdata) {
const response = await fetch("https://app-name.fly.dev/api/datapost", {
credentials: "include",
method: 'POST',
headers:{
"Content-Type": "application/json"
},
body: JSON.stringify(postdata),
})
.then((response) => {
console.log("成功");
console.log(response);
})
.catch((error) => {
console.log("失敗");
console.log(error);
});
// 以下省略
}
async function getData() {
const params = { id: document.querySelector("#product_id").value };
const query_params = new URLSearchParams(params);
const test = await fetch(`https://app-name.fly.dev/api/getdata?${query_params}`, {
credentials: "include",
})
.then((response) => {
return response;
})
.catch((error) => {
console.log(error);
});
// 以下処理省略
}
こちらがtheme app extensionsで拡張した部分のjsになります。
どちらともfetchを使用してデータのgetとpostをしています。この実装方法でローカルで動作の確認をしております。fly.ioを使用してデプロイした結果、なぜかpostの際にcrosエラーが出力されて動きません。
試したこと
Content-typeがapplication/jsonだとエラーになるという記事を見つけtext/plainへ変更したのですが効果はありませんでした。index.jsのif文がうまくいっていないのかと思いAccess-Control-Allow-Originに直接ドメイン設定してもだめでした。またAllow-Method:*も追加しましたがだめでした。headerに設定する値も減らしたり追記もしてみたりしたのですがだめでした。
crosエラー解決法調べてもheaderへAccess-Control-Allow-Originを設定するということですが、設定していてgetは動作してなぜpostが機能しないのか分かりません。
なにか記述の間違いや、このエラーの解決方法を知っている方いらっしゃいましたら、ご教授いただければ幸いです。