Leverage the Frontend (Headless Commerce) to utilize the Admin API and retrieve products from Shopify

Attempting to retrieve products from Shopify using the Admin API (GraphQL) through my frontend. I utilized the following code:

*I implemented "axios" on Quasar Framework, utilizing Headless Commerce

const response = await this.$axios({
  url: "https://healthy-food.myshopify.com/admin/api/2022-01/graphql.json",
  method: 'POST',
  headers: {
    "X-Shopify-Access-Token": "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"
  },
  data: { 
    "query": `
      { 
        products(first: 5) {
          edges {
            node {
              id
              title
            }
          }
        }
      }
    `
  }
});
console.log(response.data);

Encountered the error below:

Access to XMLHttpRequest at 'https://healthy-food.myshopify.com/admin/api/2022-01/graphql.json' from origin 'http://localhost:8080' 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.

To address this, added "Access-Control-Allow-Origin": "*" and "Content-Type": "application/json" as shown:

const response = await this.$axios({
  url: "https://healthy-food.myshopify.com/admin/api/2022-01/graphql.json",
  method: 'POST',
  headers: {
    "X-Shopify-Access-Token": "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",
    "Access-Control-Allow-Origin" : "*", // Here
    "Content-Type": "application/json" // Here
  },
  data: { 
    "query": `
      { 
        products(first: 5) {
          edges {
            node {
              id
              title
            }
          }
        }
      }
    `
  }
});
console.log(response.data);

Unfortunately, the same error persists:

Access to XMLHttpRequest at 'https://healthy-food.myshopify.com/admin/api/2022-01/graphql.json' from origin 'http://localhost:8080' 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.

Any suggestions on resolving this issue?

Answer №1

To access products from Shopify using your frontend, you cannot utilize the Admin API. Instead, you need to use the Storefront API. Replace the url with:

// "/admin" is removed
"https://healthy-food.myshopify.com/api/2022-01/graphql.json"

Make sure to update the header "X-Shopify-Access-Token" to "X-Shopify-Storefront-Access-Token":

"X-Shopify-Storefront-Access-Token": "yourStorefrontAccessToken"

For the headers, only include "X-Shopify-Storefront-Access-Token" and omit "Access-Control-Allow-Origin": "*" and "Content-Type": "application/json".

The complete code snippet that will work as expected is:

const response = await this.$axios({ // "/admin" is removed
  url: "https://healthy-food.myshopify.com/api/2022-01/graphql.json",
  method: 'POST',
  headers: { 
    "X-Shopify-Storefront-Access-Token": "yourStorefrontAccessToken"
 // Update "X-Shopify-Access-Token" to "X-Shopify-Storefront-Access-Token"
  },
  data: { 
    "query": `
      { 
        products(first: 5) {
          edges {
            node {
              id
              title
            }
          }
        }
      }
    `
  }
});
console.log(response.data);

For more information, check out the documentation.

Answer №2

Admin API can only be accessed using an admin API token.
You are limited to accessing the store front API within your theme.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

disabling past dates in Bootstrap calendar

How can I disable past dates in Bootstrap easily? <script type="text/javascript"> $(function(){ $('.datepicker').datepicker(); }); </script> Date: <input type="text" class="datepicker"></input> I have added the ...

Tips for altering the appearance of a button when moving to a related page

I have a master page with four buttons that have a mouse hover CSS property. Each button's corresponding response page is defined on the same master page. Now, I want to change the button style when the user is on the corresponding page. How can this ...

How can I resolve the issue of using string values for items inside v-autocomplete, but needing them to be numbers in v-model?

I am working with a v-autocomplete component <v-autocomplete v-model="addressRegion" :items="selectLists.regions" item-value="key" item-text="value" ></v-autocomplete> The AddressRegion is curren ...

Exploring ways to utilize Next.js (React) for formatting date and time with either Moment.js or alternate

When deciding on the best method for handling date formats in my next front-end app, should I use Moment.js or JavaScript functions? The data is sourced from the backend as the date type, and I want it to be displayed in a user-friendly format while consid ...

Creating Angular Custom Form Validation and Custom Directives

I recently created a custom validation directive and applied it to the form element like this: <form myValidations> app.directive('myValidations', function(){ return{ //require: 'ngModel', note its commented out link: f ...

Assign the two values to variables in the CSS script

My challenge lies in passing two values to the CSS within the <style> tags. The values are: (background-color: --placeholder; color: --placeholdtext;). I am able to pass either one of the values successfully, but not both at the same time. When I cop ...

Why is the bootstrap table example refusing to function properly for my situation?

I'm currently working on a project that involves a table similar to this bootstrap table. Check out the Codesandbox here Here's the template I'm using: <b-table small :fields="fields" :items="items"> <template v-slot:cell(i ...

Sending "item" properties to the "Route" element

I am looking for a way to dynamically pass a list of route objects as props for the Route components in my AppRouter component. Currently, I have the routes defined like this: export const routes = [ { path: '/about', element: About, exact: tru ...

JavaScript form button press tracker

Hello! I've been tackling a challenge involving a JavaScript function to count button clicks. The catch is, the button type is set to submit, causing the page to reload every time I click it. Below is the snippet of code that contains the problemati ...

Having trouble with implementing both filter and infinite scroll simultaneously in an Ionic list?

I've encountered an issue with my ionic hybrid app related to angularjs filters. The code snippet below showcases the problem: <input type="search" placeholder="Search personalities" ng-model="name" ng-change='alert("changed!")&apo ...

Tips for expanding the HTTP header size within Next.js

Can someone provide assistance for increasing the HTTP header size in my Next.js app? The current size is set at 16384 and I am unable to execute the necessary command node --max-HTTP-header-size=24576 server.js. Looking for help from someone with more e ...

The React JSX error you encountered is due to the missing return value at the end of the arrow function

After implementing my code, I noticed the following: books.map(({ subjects, formats, title, authors, bookshelves }, index) => { subjects = subjects.join().toLowerCase(); author = authors.map(({ name }) => name).join() ...

Django compressor throwing minification hiccup

I'm currently utilizing a tool for automatic minification known as django compressor. Unfortunately, it seems that the minification process with django compressor is causing errors to be introduced. Updated script with semicolons: Before: var ap ...

Blank YouTube Popup Modal

I am in the process of creating a pop-up modal that contains an embedded YouTube video, but my modal is not displaying properly. I am utilizing Bootstrap and have two separate sections along with JavaScript code. When the modal appears, it remains empty. I ...

Unable to convert data to a JSON string

I've created a tool for building dynamic tables: <div class="container"> <div class="row"> <div class="col"> <hr> <h3>Add your data</h3> <button id="addTd" type="button" class="btn btn-pr ...

Using Firestore startAt() with Redux: a comparison of serializable and non-serializable scenarios

I find myself at a pivotal moment in my Firebase project and am seeking some general guidance. Here are the key points as I have gathered them through my research: When it comes to Firestore queries, there is a useful feature for pagination called startAt ...

Typescript error: Cannot access property "status" on type "never".ts(2339)

Currently, I have a method that utilizes nextjs/auth to sign in with credentials from a form. However, I am encountering a type checking error Object is possibly 'undefined'.ts(2532) const doStuff = async (values: any) => { const result: S ...

Unlocking the power of popups with Angular

As a beginner in AngularJS, I have encountered an issue where a popup appears when clicking on the "login/signup" button. Now, I want the same popup to appear when clicking on the "upload resume" button as well. Below is the code that is currently working ...

The barcode is not displaying when using javascript:window.print() to print

I am currently developing a Mean Stack App where I have a requirement to display a barcode. To achieve this, I am utilizing an AngularJS directive for generating a 128 barcode, and it is being generated successfully. However, when I attempt to print by cli ...

Struggling with sending intricate model to controller via ajax request

I've encountered an issue where my model is not updating properly when I click a button. Despite logging the data in the razor file and confirming that it's correct, the controller method receives an empty model. Below is the onclick method bein ...