App reviews, troubleshooting, and recommendations
We're moving the community! Starting July 7, the current community will be read-only for approx. 2 weeks. You can browse content, but posting will be temporarily unavailable. Learn more
Solved! Go to the solution
This is an accepted solution.
This is an accepted solution.
Hyy @attaboiaj Can you help me to solve the CORS issue, I apply the your solution but still I faced the issue.
Below is my action
export async function action({ request }) {
console.log("res----->", request)
if (request.method === "OPTIONS") {
const response = json({}, { status: 200 });
return await cors(request, response, corsOptions);
}
if (request.method !== "POST") {
return await cors(
request,
json({ success: false, message: "Method not allowed" }, { status: 405 }),
corsOptions,
);
}
try {
const body = await request.json();
const { shopId, offerData } = body;
if (!shopId || !offerData || typeof offerData !== "object") {
return await cors(
request,
json(
{ success: false, message: "Invalid request data." },
{ status: 400 },
),
corsOptions,
);
}
const session = new Session({
id: SHOPIFY_CONFIG.sessionId,
shop: SHOPIFY_CONFIG.shop,
state: "",
isOnline: false,
accessToken: SHOPIFY_CONFIG.accessToken,
});
const shopify = shopifyApi({
apiKey: SHOPIFY_CONFIG.apiKey,
apiSecretKey: SHOPIFY_CONFIG.apiSecretKey,
hostName: SHOPIFY_CONFIG.hostName,
apiVersion: LATEST_API_VERSION,
isEmbeddedApp: true,
});
const admin = new shopify.clients.Graphql({ session });
let mutation;
let variables;
let errorPath;
let successPath;
console.log("offerData---->", offerData);
const percentageDiscountVariable = createBasicCodeDiscount({
title: offerData.discountText,
code: generateDiscountCode(
offerData.discountValue,
offerData.discountText,
),
percentage: getPercentageFromValue(offerData.discountValue),
usageLimit: 100,
appliesOncePerCustomer: true,
productDiscounts: offerData.discountCombinations.productDiscounts,
orderDiscounts: offerData.discountCombinations.orderDiscounts,
shippingDiscounts: offerData.discountCombinations.shippingDiscounts,
});
const fixedAmountDiscountVariable = createFixedAmountDiscount({
title: offerData.discountText,
code: generateDiscountCode(
offerData.discountValue,
offerData.discountText,
),
amount: offerData.discountValue,
usageLimit: 100,
appliesOncePerCustomer: true,
productDiscounts: offerData.discountCombinations.productDiscounts,
orderDiscounts: offerData.discountCombinations.orderDiscounts,
shippingDiscounts: offerData.discountCombinations.shippingDiscounts,
});
const { lowestProduct, remainingProductIds } =
getLowestPricedProductWithOthers(offerData.selectedOfferProducts);
const automaticBxgyDiscountVariable =
createAutomaticBxgyDiscountCheapestItemFree({
discountText: offerData.discountText,
remainingProductIds,
lowestProductId: lowestProduct?.productId,
productDiscounts: offerData.discountCombinations.productDiscounts,
orderDiscounts: offerData.discountCombinations.orderDiscounts,
shippingDiscounts: offerData.discountCombinations.shippingDiscounts,
});
const freeShippingCodeDiscountVariable =
createFreeShippingCodeDiscountVariable(
offerData.discountText,
offerData.discountCombinations.productDiscounts,
offerData.discountCombinations.orderDiscounts,
);
switch (offerData.discountType) {
case "percentage":
mutation = AMMOUNT_OFF_PERCENTAGE;
variables = { basicCodeDiscount: percentageDiscountVariable };
errorPath = "discountCodeBasicCreate.userErrors";
successPath = "discountCodeBasicCreate.codeDiscountNode.id";
break;
case "fixed":
mutation = AMMOUNT_OFF_FIXED;
variables = { basicCodeDiscount: fixedAmountDiscountVariable };
errorPath = "discountCodeBasicCreate.userErrors";
successPath = "discountCodeBasicCreate.codeDiscountNode.id";
break;
case "cheapest item free":
mutation = CHEAPEST_ITEM_FREE_MUTATION;
variables = { automaticBxgyDiscount: automaticBxgyDiscountVariable };
errorPath = "discountAutomaticBxgyCreate.userErrors";
successPath = "discountAutomaticBxgyCreate.automaticDiscountNode.id";
break;
case "free shipping":
mutation = FREE_SHIPPING_MUTATION;
variables = {
freeShippingCodeDiscount: freeShippingCodeDiscountVariable,
};
errorPath = "discountCodeFreeShippingCreate.userErrors";
successPath = "discountCodeFreeShippingCreate.codeDiscountNode.id";
break;
default:
return await cors(
request,
json(
{ success: false, message: "Unsupported discount type." },
{ status: 400 },
),
corsOptions,
);
}
console.log("mutation---->", mutation);
const response = await admin.query({
data: {
query: mutation,
variables,
},
});
const data = response.body?.data;
const getFromPath = (obj, path) =>
path.split(".").reduce((acc, key) => acc && acc[key], obj);
const userErrors = getFromPath(data, errorPath);
if (userErrors?.length > 0) {
return await cors(
request,
json({ success: false, errors: userErrors }, { status: 400 }),
corsOptions,
);
}
const discountId = getFromPath(data, successPath);
console.log("discountId----->", discountId);
return await cors(
request,
json(
{
success: true,
discountId,
},
{ status: 201 },
),
corsOptions,
);
} catch (error) {
console.log("error ==== >", error);
return await cors(
request,
json({ success: false, message: error.message }, { status: 500 }),
corsOptions,
);
}
below is my .liquid file from that i call the api
async addBundleToCart() {
const selectedProducts = this.offerProducts.selectedOfferProducts;
try {
// 1. Add selected products to cart
const cartAddData = selectedProducts.map((product) => ({
id: product.variants[0].id.split('/').pop(),
quantity: 1,
}));
console.log('cartAddData---->', cartAddData);
const addResponse = await fetch('/cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({ items: cartAddData }),
});
if (!addResponse.ok) throw new Error('Cart add failed');
console.log('🛒 Products added to cart');
// 2. Call your discount API
const shopId = '{{ shop.domain }}';
{% comment %} const apiURL = 'https://origin-army-meat-basement.trycloudflare.com'; {% endcomment %}
console.log('reached here 1');
const discountResponse = await fetch(`https://reggae-rapid-rover-p.trycloudflare.com/api/discountCreate`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
});
console.log('✅ discountResponse------>', discountResponse);
if (!discountResponse.ok) {
throw new Error( 'Discount API failed');
}
console.log('✅ Discount API triggered');
} catch (error) {
console.error('❌ Error during bundle add:', error);
}
}
Sorry dude I wasn't really active here for a while, did you find the solutions?
I would highly suggest to put all your errors and ask Claude it has all the answers