繁体   English   中英

在 shopify 中将数据从前端发送到后端

[英]Sending data from frontend to backend in shopify

我正在开发一个带有节点的应用程序并做出反应。 在这个应用程序中,我使用 fetch function 创建了一个 scriptTag,以在按下特定按钮时获取客户 ID 和产品 ID。 现在,当我获取该数据时,我想将其存储在我的 firebase 数据库中,我无法将其导入我的脚本标记文件中,因为它位于前端。 因此,我需要将数据从我的前端发送到应用程序的后端,但我很困惑,如果我使用 fetch function 发出 POST 和 GET 请求,我应该使用什么 URL? 此外,获取 function 甚至可以发布变量值吗?

Scripttag.js

const header = $('header.site-header').parent();

header.prepend('<div>Hello this is coming from the public folder </div>').css({'background-color':'orange', 'text-align': 'center'})

function addWishList(customer, productid){
/*
  fetch(`url`, {
    method: 'POST',
    headers: {
      'Content-Type': ,
      "X-Shopify-Access-Token": ,
    },
    body: 
    }})
  })

*/

    console.log('adding item to the wishlist!!')
}

function removeWishList(){
    console.log('removing item from the wishlist!!')
}
 var wishbtn = document.querySelector('.wishlist-btn')
 wishbtn.addEventListener('click', function(){
     if(this.classList.contains('active')){             //condition to check if the button is already pressed
        removeWishList();
        this.classList.remove('active');
        this.innerHTML = 'Add to wishlist'
     }
     else{
        var customer = wishbtn.dataset.customer;
        if(customer == null || customer == ''){
            console.log('Please log in to add this item to your wishlist')
        }
        else{
            var productid = wishbtn.dataset.product;
            this.classList.add('active');      //when the user presses add to wishlist button, it add active to the button's class
            this.innerHTML = 'Remove from wishlist'
            addWishList(customer, productid);
        }
     }
     
 })

将数据从前端发送到后端的最佳方式是使用 Shopify 合作伙伴仪表板中提供的代理选项。

在此处输入图像描述

这样您就可以留在 Shopify 环境中,因为它会将特定的 arguments 传递给请求,您可以检查该请求是否真的来自 Shopify 并且您不必担心保护它免受外部请求的影响。

因此,例如,您将向/apps/YOUR_CUSTOM_PATH发出 fetch 请求,这将代理到您的 URL https://example.com/custom_path您将在其中处理请求。

您可以在此处查看更多信息: https://shopify.dev/tutorials/display-data-on-an-online-store-with-an-application-proxy-app-extension

您也可以为您的应用程序创建一条公共路线,该路线可以从任何地方请求并允许 CORS 但这样做通常需要更多的工作......所以选择你的毒药。

请记住,在创建代理页面时,您需要在商店中重新安装应用程序才能生效。

PS:永远不要在前端使用访问令牌,它不应该出现在前端。 AccessToken 只是与 API 通信的后端方式!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM