Shopware前台插件window.router报错:Cannot read properties of undefined
Shopware前台插件路由调用报错的解决办法
1. 先检查路由键名是否写错
你用的frontend.api.name大概率是占位符写错了——Shopware的前台API路由键都是frontend.api.xxx格式的具体名称,比如用户登录是frontend.api.customer.login,获取产品列表是frontend.api.product.search。先确认你要调用的API对应的正确路由键是什么。
2. 确认window.router是否已经加载完成
如果控制台输入window.router返回undefined,说明你的代码执行时机太早,Shopware的路由还没初始化好。把调用逻辑放到插件的init钩子或者监听shopware:ready事件里:
// 示例:放到插件初始化钩子中 Shopware.PluginManager.register('your-plugin-name', { init() { // 这里再执行路由相关调用 this._client.post(window.router['frontend.api.your-actual-key'], payload, this._setContent.bind(this)); } }); // 或者用事件监听 document.addEventListener('shopware:ready', () => { this._client.post(window.router['frontend.api.your-actual-key'], payload, this._setContent.bind(this)); });
3. 验证自定义API路由是否正确注册
如果是自己开发的API,要确认路由在插件的src/Resources/config/routes.xml里配置正确:
<route id="frontend.api.your-custom-api" path="/api/v{version}/your-api-path" methods="POST"> <default key="_controller">YourPlugin\Controller\FrontendApiController::yourAction</default> </route>
配置完记得清理Shopware缓存,确保路由被系统加载。
4. 应急方案:直接拼接API路径
如果以上步骤都没解决,可以跳过路由生成,直接写死API路径(不推荐长期用,维护性差):
const apiPath = `/api/${Shopware.Context.api.apiVersion}/your-api-path`; this._client.post(apiPath, payload, this._setContent.bind(this));
内容的提问来源于stack exchange,提问作者DevOPlug
相关产品推荐
相关产品推荐

