How to trigger async GET requests to store data events from a page's onClick event?

Shopify Partner
4 0 1

This is the repository in question

 

The app writes the data we need into data.json (in the root directory) upon install, but I need the data.json to be overwritten on demand (i.e. onClick event). Is that even possible?

 

I have tried transposing the GET request function from server.js into a page (index.js) file, but upon compiling the page and pressing the button with the bound function, I get these errors in the console, pertaining to CORS policies. I don't know how the initial GET request upon install in server.js bypassed CORS, but I need to do the same thing in index.js.

Capture.PNG

server.js

server.use(
createShopifyAuth({
apiKey: SHOPIFY_API_KEY,
secret: SHOPIFY_API_SECRET_KEY,
scopes: ['read_products', 'write_products', 'read_orders', 'write_orders'],
async afterAuth(ctx) {
const { shop, accessToken } = ctx.session;
ctx.cookies.set('shopOrigin', shop, { httpOnly: false });
ctx.cookies.set('accessToken', accessToken, {httpOnly: false})
const options = {
method: 'GET',
credentials: 'include',
headers: {
'X-Shopify-Access-Token': accessToken,
'Content-Type': 'application/json',
},
};

await fetch(`https://${shop}/admin/orders.json?status=any`, options)
.then((response) => response.json())
.then((data) => {
fs.writeFile('./data', JSON.stringify(data, null, 4), (error) => {
if (error) {
console.error(error);
return;
}
console.log('File has been created');
});
})
.catch((error) => console.error( error));
ctx.redirect('/');
},
}),
);

 index.js

async rewrite(){
console.log("rewrite");
const options = {
method: 'GET',
credentials: 'include',
headers: {
'X-Shopify-Access-Token': cookies.get('accessToken'),
'Content-Type': 'application/json',
},
};
await fetch(`https://${cookies.get('shopOrigin')}/admin/orders.json?status=any`, options)
.then((response) => response.json())
.then((data) => {
fs.writeFile('./data', JSON.stringify(data, null, 4), (error) => {
if (error) {
console.error(error);
return;
}
console.log('File has been created');
});
})
.catch((error) => console.error( error));
}
0 Likes