在shopware 6中,我想从后端/管理页面(javascript)调用后端/管理API控制器。通过内置的getter函数使用相对路径的正确方式是什么?
只有当商店在/上时,抓取/api/v1才有效,而当它在子文件夹中时,则不起作用。
fetch('/api/v1/my-plugin/my-custom-action', ...)发布于 2020-08-03 14:17:37
最佳实践是编写自己的JS服务来处理与api端点的通信。
我们有一个抽象的ApiService类,你可以继承它。您可以查看the platform中的CalculatePriceApiService示例。对于您来说,实现可能如下所示:
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,包括子文件夹,并且它将自动使用您的商店软件版本支持的apiVersion。这意味着每当有新的apiVersion版本可用时,ApiService在路由中使用的api就会增加,这意味着您需要在该api版本的后端路由注释中使用通配符。
最后,请记住,您需要注册该服务。这就是documented here。对于您来说,这可能是这样的:
Shopware.Application.addServiceProvider('myPluginService', container => {
const initContainer = Shopware.Application.getContainer('init');
return new MyPluginApiService(initContainer.httpClient, Shopware.Service('loginService'));
});发布于 2020-08-02 21:58:32
如果您正在谈论已实现的自定义操作,则需要在Resources\config\routes.xml的routes.xml中定义路由(使用注释)和注册控制器。
请按照该文档https://docs.shopware.com/en/shopware-platform-dev-en/how-to/api-controller进行操作
https://stackoverflow.com/questions/63215221
复制相似问题