How can I resolve the CORS policy error in Shopify script tags?

How can I resolve the CORS policy error in Shopify script tags?

FaizaBashir
Shopify Partner
39 0 3

Hello,

 I am new to shopify app development and I am develping a test app in react that will add a button under add to cart button on product page. In web/frontend/page/index.jsx i have added below code for script tags. I know this is not the right file please let me know where should write this code to add script tags so its loaded automatically when app is insatlled. I am getting this error

Access to XMLHttpRequest at 'https://test-shop.myshopify.com/admin/api/2021-04/script_tags.json' from origin 'https://682ed-115-186-141-90.ap.ngrok.io' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

 

I have setup the proxy settings in app setup and added the ngrok url https://682ed-115-186-141-90.ap.ngrok.io in proxu url but still getting same error.

 

web/frontend/page/index.js

 

const url = `https://{shop}/admin/api/2021-04/script_tags.json`;
  const src = 'https://{app-name/scripts/test-script.js';
  let token="******************";
  let scriptTagExist = false;
  const shopifyHeader = (token) => ({
      'Content-Type': 'application/json',
      'X-Shopify-Access-Token': token,
  });
  const scriptTagBody = JSON.stringify({
      script_tag: {
          event: 'onload',
          src,
      },
  });
  const getScriptTags = await axios.get(url, { headers: shopifyHeader(token)});
  getScriptTags.data.script_tags.map((script) => {
      if(script.src == src) {
          scriptTagExist = true;
      }
  });
  if(!scriptTagExist) {
      await axios.post(url, scriptTagBody, { headers: shopifyHeader(accessToken) })
          .then(response => { console.log(response); })
          .catch(error => console.log(error));
  } else {
      return JSON.stringify({scriptTagStatus: true});
  }
Reply 1 (1)

jeff0723
Shopify Partner
36 1 7

The CORS issue is due to ngrok not your api header. You just simply change ngrok link to localhost and that can be solved.

Indie developer.
Seeking to solve merchants' problems.