Shopware 6 后端控制器路径

Shopware 6 backend controller path

在 Shopware 6 中,我想使用 JavaScript 从后端/管理页面调用后端 (/admin) API 控制器。使用相对路径的正确方法是什么,可能使用内置 getter 函数?

仅当商店位于 / 上时才能获取 /api/v1,但当它位于子文件夹中时则无效。

fetch('/api/v1/my-plugin/my-custom-action', ...)

如果您谈论的是您实施的自定义操作,则需要在 Resources\config\routes.xml.[= 的 routes.xml 中定义路由(使用注释)并注册控制器11=]

请遵循该文档 https://docs.shopware.com/en/shopware-platform-dev-en/how-to/api-controller

最佳做法是编写自己的 JS 服务来处理与 api 端点的通信。

我们有一个抽象ApiServiceclass,你可以继承自。您可以查看 CalculatePriceApiService 以获取 the platform 中的示例。 对于您来说,实现可能如下所示:

class MyPluginApiService extends ApiService {
    constructor(httpClient, loginService, apiEndpoint = 'my-plugin') {
        super(httpClient, loginService, apiEndpoint);
        this.name = 'myPluginService';
    }

    myCustomAction() {
        return this.httpClient
            .get('my-custom-action', {
                headers: this.getBasicHeaders()
            })
            .then((response) => {
                return ApiService.handleResponse(response);
            });
    }
}

请注意,在构造函数的第一行中,您的 api 服务已预先配置为与您的 my-plugin 端点通信,这意味着您可以在以下所有请求中使用相对路由路径。

还请记住,抽象 ApiService 将负责解析用于请求的配置。特别是这意味着 ApiService 将使用正确的 BaseDomain 包括子文件夹,并且它将自动使用您的 shopware 版本支持的 apiVersion。这意味着每次有新的 api 版本可用时,ApiService 在路由中使用的 apiVersion 都会增加,这意味着您需要在 api 的后端路由注释中使用通配符版本。

最后请记住,您需要注册该服务。即documented here。 对你来说,这可能是这样的:

Shopware.Application.addServiceProvider('myPluginService', container => {
    const initContainer = Shopware.Application.getContainer('init');
    return new MyPluginApiService(initContainer.httpClient, Shopware.Service('loginService'));
});