如何从Shopify Liquid主题向Remix应用的认证路由发起请求?
解决方案:为Shopify Liquid中的Fetch请求添加认证
首先纠正你当前Fetch请求的一个错误:你用JSON.stringify()处理请求体,但设置了Content-Type: multipart/form-data,这会导致后端解析request.json()失败,应该改为application/json。
接下来针对authenticate.admin导致的重定向问题,提供两种可行的解决方案:
方案1:使用Shopify App Proxy(推荐)
因为你的Remix应用是Shopify App,利用Shopify的App Proxy功能,能让请求自动携带认证信息,无需手动处理:
- 在Shopify App后台的「App setup」→「App proxy」中配置代理:
- 填写子路径(比如
your-app-slug) - 目标URL填写你的Remix API路由地址(
https://my-proxy-url.trycloudflare.com/api/entrants)
- 填写子路径(比如
- 修改Liquid中的Fetch请求URL为Shopify代理地址:
fetch('/apps/your-app-slug/api/entrants', { method: 'post', body: JSON.stringify({...}), headers: { 'Content-Type': 'application/json', } });
Shopify会自动为转发到你App的请求添加X-Shopify-Access-Token、X-Shopify-Shop-Domain等认证头,authenticate.admin就能正常验证通过,不会触发重定向。
方案2:手动传递Admin API访问令牌
如果不想使用App Proxy,可以手动获取并携带Admin API令牌:
- 在Remix应用中新增一个路由(比如
/api/get-token),用于返回当前店铺的访问令牌:
import { authenticate } from 'app/shopify.server'; import { ActionFunctionArgs } from '@remix-run/node'; export const action = async ({ request }: ActionFunctionArgs) => { const { session } = await authenticate.admin(request); return new Response(JSON.stringify({ token: session.accessToken }), { headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': 'https://你的店铺域名.myshopify.com', // 限制来源提升安全性 } }); };
- 在店铺后台的App页面中调用该路由获取令牌,将令牌存储到主题可用的变量中(比如通过App嵌入脚本或Liquid代码片段)
- 在Liquid的Fetch请求中携带认证头:
fetch('https://my-proxy-url.trycloudflare.com/api/entrants', { method: 'post', body: JSON.stringify({...}), headers: { 'Content-Type': 'application/json', 'X-Shopify-Access-Token': '{{ 存储令牌的变量 }}', 'X-Shopify-Shop-Domain': '{{ shop.domain }}' } });
注意:这种方式要确保令牌的安全性,建议使用短期有效令牌,并严格限制请求来源。
另外,建议将Remix路由中的Access-Control-Allow-Origin从*改为你的店铺域名,避免跨域安全风险。
内容的提问来源于stack exchange,提问作者Michael Lynch
相关产品推荐
相关产品推荐

