How can I add a product on the product page using Ajax API?

How can I add a product on the product page using Ajax API?

plus13
Shopify Partner
7 1 1
I want to add an product at the product page. I couldn't do, if I did do like that page(https://shopify.dev/api/ajax/reference/cart).

my source is like that

const addUrl = window.Shopify.routes.root + 'cart/add.js';

export default class CartModel {
  constructor() {
   ......
  }

addProduct(btn) {
    const toSend = {'items': [
       id: xxxxxx,
       quantity: 1
    ]};
  

    fetch(addUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(toSend)
    })
    .then(response => {
    ....
    })
    .then(myBlob => {
      .....
    })
    .catch((error) => {
      ......  
    });
  }
}
but I got that error
Uncaught TypeError: Cannot read properties of undefined (reading 'routes')
before I could but now I cant. I have to include something?
Please tell me why.
Reply 1 (1)

plus13
Shopify Partner
7 1 1

change

const addUrl = window.Shopify.routes.root + 'cart/add.js';

to

const addUrl = '/cart/add.js';

 
I could. Is it the solution?