如何在VueStorefront的Shopware PWA中调用自定义Store API路由?
Shopware 6 PWA调用自定义Store API路由的正确方式
核心结论:不需要手动指定完整URL
Shopware PWA的内置请求工具已经默认配置了Store API的基础地址,直接使用Swagger中显示的路由相对路径即可发起请求。
具体实现方法
方法1:使用官方推荐的useFetch Composable
这是Shopware PWA提供的专门用于API请求的组合式函数,内置加载、错误状态管理,语法简洁:
<script setup> import { useFetch } from '@shopware-pwa/composables' // 替换为Swagger中你的自定义路由路径(无需带store-api前缀) const { data: customData, error, loading } = useFetch('/my-custom-store-route') </script> <template> <div v-if="loading">加载中...</div> <div v-if="error">请求失败:{{ error.message }}</div> <div v-if="customData"> <pre>{{ customData }}</pre> </div> </template>
方法2:使用内置的Axios实例
如果需要更灵活的请求控制(比如自定义请求头、POST请求等),可以用PWA封装好的Axios实例:
<script setup> import { useAxios } from '@shopware-pwa/composables' import { ref, onMounted } from 'vue' const { axiosInstance } = useAxios() let customData = ref(null) let requestError = ref(null) async function fetchCustomData() { try { // 同样使用相对路径,无需完整URL const response = await axiosInstance.get('/my-custom-store-route') customData.value = response.data } catch (err) { requestError.value = err console.error('获取自定义数据失败:', err) } } // 页面挂载时触发请求 onMounted(() => { fetchCustomData() }) </script>
关键注意事项
- 路由路径匹配:去
store-api/_info/swagger.html找到你的自定义路由,复制其路径(例如/my-custom-route),确保请求时使用的路径与之一致,不要包含store-api前缀——因为PWA的请求工具已经将基础地址设为store-api。 - 权限验证:如果你的自定义路由需要认证,PWA的请求工具会自动携带用户的认证凭证(如会话Cookie或Bearer Token),无需手动处理。
- 路径验证:若不确定基础地址配置,可以在控制台打印
axiosInstance.defaults.baseURL确认,确保相对路径拼接后是正确的完整API地址。
内容的提问来源于stack exchange,提问作者Johan
相关产品推荐
相关产品推荐

