Hello,
I am trying to get a collection into my checkout ui extension. I have multiple problems which I do not get around and do not really find suitable and working answers online.
File: extensions/{extension-name}/src/Checkout.tsx
const fetchData = async () => {
const token = await sessionToken.get();
const response = await fetch(`${process.env.APP_URL}/admin-api`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token,
'Access-Control-Allow-Origin': '*',
}
}).then((response) => {
console.log(response)
}).catch(console.error)
}
I am not able to make a GET request to the admin-api.js file. This is most likely caused by cors. I do not really understand why, since my understanding is that ‘Access-Control-Allow-Origin’: ‘*’ should fix that problem.
Error:
Access to fetch at ‘https://soundtrack-omissions-outstanding-unwrap.trycloudflare.com/admin-api’ from origin ‘https://extensions.shopifycdn.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.
File: app/routes/admin-api.jsx
This is the function which should be able to fetch data with GraphQL.
import { json } from "@remix-run/node";
import {authenticate} from "app/shopify.server";
export async function loader({ request }) {
const { admin } = await authenticate.admin(request);
const response = await admin.graphql(`
#graphql
query {
collections(first: 5) {
edges {
node {
id
title
handle
updatedAt
sortOrder
}
}
}
}
`);
const parsedResponse = await response.json();
console.log(parsedResponse.data);
return json({
products: parsedResponse.data,
});
}
If I open /{store-name}/apps/checkout-validation-extension-2/admin-api in the browser, the console.log displays the collections in the terminal just fine.
However, if I call the file via the checkout (which is odd since it should not work due to the cors error at all?) the function breaks at "const { admin } … ". If I add a console.log before that, it will be displayed. Everything after is not executed.
I have api_access in the toml file set to true and “Allow network access..” in the partners dashboard activated aswell.
Any help is appreciated since I am not able to figure it out myself.
Thank you!