Search code examples
vue.jsaxiosshopifyshopify-api

Get shopify admin endpoint in axios in vue


How do you do this?

Use Admin API from Frontend(Headless Commerce) to get products from Shopify

<template>
    <div>{{ data }}</div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'ShopifyResult',
  data () {
    return {
      data: null
    }
  },
  mounted () {
    const url = 'https://a-shopify-store.myshopify.com/admin/api/2021-10/checkouts.json';
    axios({
        method:'get',
        url,
        headers: {
        "Content-Type": "application/json",
        "X-Shopify-Access-Token": 'API_ADMIN_ACCESS_TOKEN_HERE',
        },
    }).then((result) => {
        console.log(result.data)
    }).catch(error => {
        console.log(error)
    });
  }
}
</script>

This is what I get:

Access to XMLHttpRequest at 'https://a-shopify-store.myshopify.com/admin/api/2021-10/checkouts.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. ShopifyResult.vue?4048:27 AxiosError

Why is CORS involved? I have a all the appropriate keys. How do you do this?

I also found

https://community.shopify.com/c/technical-q-a/vue-axios-get-requests-how-to-secure-apikey-and-apipass/td-p/689016

no answers.....


Solution

  • https://community.shopify.com/c/shopify-apis-and-sdks/using-apis-from-a-different-origin-domain/td-p/502781

    Think of it this way:

    Storefront API is a public API and the token for it is meant to be used on the client side.

    Admin API is a private API and the token is not meant to be shared publicly. If you share this token to everyone by making requests from the browser, they can potentially access private information about your store, financial information, CUSTOMER information etc.

    This could lead to both inconvenience to your customers as they would be subject to fraud as well as you could run into legal issues if someone decides to sue you because of it.

    Hence, Shopify throws a CORS error when detecting that you use a browser to send a request to a private API. While the CORS error might not be the most appropriate response here, it is valid for them to deny your request.

    Hope that clarifies the issue for others encountering this error.