New Shopify Certification now available: Liquid Storefronts for Theme Developers

CORS POLICY ERROR for 'X-Shopify-Access-Token'

mohd-Shahrukh
Shopify Partner
3 0 0
I want to use shopify API from my application frontend as I only listing the products for now. we do not have any backend and I am using simple fetch request for that but I am getting "CORS ORIGIN" error when I call the API and If I call the same API from CURL OR Postman I am getting desire output. Please guide me on this issue. below is my code for calling API and ERROR also I am mentioning.
 
return await fetch('https://{my-shop}.myshopify.com/admin/api/2023-04/products.json', {
  method: 'GET',
  headers: {    'Content-Type': 'application/json'
       'X-Shopify-Access-Token': 'access-token',
},
  }).then((response) => {  return response.json(); })
 
 
Error : Access to fetch at 'https://{my-shop}.myshopify.com/admin/api/2023-04/products.json' from origin 'http://192.168.230.62:9684' has been blocked by CORS policy: Request header field x-shopify-access-token is not allowed by Access-Control-Allow-Headers in preflight response.
Replies 3 (3)
Liam
Shopify Staff
Shopify Staff
1917 204 579

Hi Mohdyou,

 

Even if your application is mostly client-side, for tasks that involve calling APIs, you should have a server-side component to your app that securely stores your credentials and makes requests to the Shopify API. The frontend of your application can then make requests to your own backend, which in turn calls the Shopify API and returns the response back to your frontend. This way, the actual call to Shopify's API is made server-side, avoiding CORS issues and keeping your credentials secure.

 

Since you do not have any backend, you might want to consider using serverless functions (like Vercel or Netlify functions) to handle these kinds of tasks.

 

Hope this helps!

Liam | Developer Advocate @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

mohd-Shahrukh
Shopify Partner
3 0 0

Hello Liam,

I tried using vercel for the deployment of my code.

I am getting below error: 
"Access to fetch at 'https://croquet-microverse.myshopify.com/admin/api/2023-04/products.json' from origin 'https://croquet-microverse-9n1n9r8js-soni-shivani.vercel.app' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."

 

also I tried to resolve this by adding this code in my API call 
I have also attached my code's screenshot please check.api-calling-code.png

 

Thanks & regards 

Mohd Shahrukh

mohd-Shahrukh
Shopify Partner
3 0 0

Hey, 

 

Can you please guide me to resolve this issue. 

Thank you