Having trouble with API Call Sveltekit

Having trouble with API Call Sveltekit

oso
Visitor
1 0 0

Hi,

 

When i use Postman to do API call, it works and i get data back but when i use fetch in my Sveltekit app, i get errors: '[API] Invalid API key or access token (unrecognized login or wrong password)'.

 

I am using this format for the call https://{username}:{password}@{shop}.myshopify.com/admin/api/2021-10/graphql.json

 

This is my fetch

 

try {
        const result = await fetch(import.meta.env.VITE_SHOPIFY_API_ENDPOINT, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Shopify-Storefront-Access-Token': import.meta.env.VITE_SHOPIFY_STOREFRONT_API_TOKEN
            },
            body: JSON.stringify({ query, variables })
        }).then((res) => res.json());

        if (result.errors) {
            console.log({ errors: result.errors });
        } else if (!result || !result.data) {
            console.log({ result });
            return 'No results found.';
        }
        console.log(result);
        return result.data;
    } catch (error) {
        console.log(error);
    }
Reply 1 (1)

rvncmd
Visitor
1 0 0

@oso this is what worked for me. If you are working off that log rocket blog I had a lot of trouble with that setup as well.

Here is what is working for me at the moment but I am still working on it.

 

 

<script context="module">
	/**
	 * @type {import('@sveltejs/kit').Load}
	 */
	export async function load({ page, fetch, session, stuff }) {
		var myHeaders = new Headers();
		myHeaders.append('Content-Type', 'application/json');
		myHeaders.append('X-Shopify-Storefront-Access-Token', `${import.meta.env.VITE_SHOPIFY_STOREFRONT_API_TOKEN}`);

		var graphql = JSON.stringify({
			query: `{
         products(sortKey: TITLE, first: 100) {
          edges {
            node {
              id
              handle
              description
              title
              totalInventory
              productType
              variants(first: 5) {
                edges {
                  node {
                    id
                    title
                    quantityAvailable
                    price
                  }
                }
              }
              priceRange {
                maxVariantPrice {
                  amount
                  currencyCode
                }
                minVariantPrice {
                  amount
                  currencyCode
                }
              }
              images(first: 1) {
                edges {
                  node {
                    src
                    altText
                  }
                }
              }
            }
          }
        }
    }`,
			variables: {}
		});
		var requestOptions = {
			method: 'POST',
			headers: myHeaders,
			body: graphql,
			redirect: 'follow'
		};

    const url = `${import.meta.env.VITE_SHOPIFY_API_ENDPOINT}`

		const products = await fetch(
			`${import.meta.env.VITE_SHOPIFY_API_ENDPOINT}/graphql.json`,
			requestOptions
		)
			.then((response) => response.text())
			.then((result) => {
				return result;
			})
			.catch((error) => console.log('error', error));

		return {
			props: {
				products: JSON.parse(products)
			}
		};
	}
</script>

<script>
  export let products;
</script>

<h1>Products</h1>

<p>Product List</p>
{#each products.data.products.edges as product}
<p>{product.node.title} </p>
{/each}

Right now I am trying to get a products.json.js to store the data and then pass to the products.svelte file but I have not be successful. Let me know if you find a better way.