无法通过 Shopware 6 中的 XmlHttpRequest 请求 PageController

PageController can't be requested via XmlHttpRequest in Shopware 6

我正尝试在最新的 Shopware 6.2.2 上向我的自定义 StorefrontController 发送请求,但我收到以下错误:

PageController can't be requested via XmlHttpRequest.

我正在做一个来自自定义 JS 插件的常规 httpClient 请求:


export default class MyCustomPlugin extends Plugin {

  static options = {
      dataUrl: '', // comes from the twig as "path('frontend.path.to.route')"
      product: null,
      params: {},
      loadingIndicatorClass: 'is-loading',
      responseSelector: 'some-selector-class'

  }

  init () {
      // this.el.innerHTML = LoadingIndicator.getTemplate()
      this.httpClient = new HttpClient()
      const query = querystring.stringify(this.options.product)
      this.sendDataRequest(query)
  }

  /**
   * Add classes to add loading styling.
   * Prevents the user from clicking filter labels during filter request.
   */
  addLoadingIndicatorClass () {
      this.el.classList.add(this.options.loadingIndicatorClass)
  }

  /**
   * Remove loading styling classes.
   */
  removeLoadingIndicatorClass () {
      this.el.classList.remove(this.options.loadingIndicatorClass)
  }

  /**
   * Send request to get filtered product data.
   *
   * @param {String} filterParams - active filters as querystring
   */
  sendDataRequest (filterParams) {

      this.addLoadingIndicatorClass()

      this.httpClient.abort()
      this.httpClient.get(`${this.options.dataUrl}?${filterParams}`, (response) => {
          this.renderResponse(response)
          this.removeLoadingIndicatorClass()
      })
  }

  /**
   * Inject the HTML of the response to the element.
   *
   * @param {String} response - HTML response
   */
  renderResponse (response) {
      ElementReplaceHelper.replaceFromMarkup(response, this.options.responseSelector, false)
      window.PluginManager.initializePlugins()
  }
}

这是我的 StorefrontController 路线:

    /**
     * @Route("/path/to_route", name="frontend.path.to.route", methods={"GET"})
     */
    public function someAction(Request $request, Context $context): JsonResponse

谁能告诉我为什么请求不成功?我想向 Shopware 6 中我自己的控制器发送一个简单的 AJAX 请求。

谢谢!

尝试添加:

defaults={"XmlHttpRequest"=true} 到您的路线。

因此在更改之后您将拥有:

/**
* @Route("/path/to_route", name="frontend.path.to.route", methods={"GET"}, defaults={"XmlHttpRequest"=true})
*/

还要确保使用 @RouteScope 注释在控制器中正确定义了范围。由于您的代码是店面 JavaScript 插件,因此它应该定义 storefront 范围。