wubinworks / module-webapi
[1] 添加对 `application/wubinworks-x-www-form-urlencoded` 的支持。 [2] 条件性地修改 JSON 输出行为。请参阅 https://github.com/wubinworks/magento2-module-webapi
Requires
- php: >=7.3
- magento/framework: *
- magento/module-webapi: *
This package is not auto-updated.
Last update: 2024-09-21 15:05:22 UTC
README
(仅适用于 REST 端点。)
本模块设计为开发其他模块的依赖。
1. 支持 Content-Type: application/x-www-form-urlencoded
Magento WEBAPI_REST 默认支持 application/json
、application/xml
、application/xhtml+xml
、text/xml
内容类型,其他任何内容类型都会导致错误消息,例如 "message": "Server cannot understand Content-Type HTTP header media type application/x-www-form-urlencoded"
然而,application/x-www-form-urlencoded
在 表单 中常用,许多第三方软件只能 POST 这种内容类型。
如何使用?
只需使用 Content-Type: application/x-www-form-urlencoded
正常发送请求,并添加一个额外的自定义头部 Use-Deprecated-Content-Type: 1
。
注意:您必须在请求中包含 Use-Deprecated-Content-Type: 1
头部,否则它将不起作用!
2. 条件性地修改 JSON 输出行为
当开发服务类(通常是一个名为 someActionManagement.php 的文件在模型文件夹中)时,如果它返回如下数组,
return [
'code' => 0,
'message' => 'Success',
'data' => [
'customer_id' => 1
]
];
Magento 会将返回的数据包围在一个数组括号中,并且属性名会被删除。
输出
[
0,
"Success",
{
"customer_id": 1
}
]
这可能是您不希望看到的。
如果服务类返回
return [
'dummy' => [
'code' => 0,
'message' => 'Success',
'data' => [
'customer_id' => 1
]
]
];
则输出变为
[
{
"code": 0,
"message": "Success",
"data": {
"customer_id": 1
}
}
]
注意最外层的 []
,许多第三方软件期望输出是一个对象。
如何使用?
在输出数组中添加 'type' => 'simple_array'
,即,
return [
'code' => 0,
'message' => 'Success',
'data' => [
'customer_id' => 1
],
'type' => 'simple_array' // Add this key-value pair
];
那么输出将是
{
"code": 0,
"message": "Success",
"data": {
"customer_id": 1
}
}
注意:JSON 输出将不会包含 "type": "simple_array"
,它被删除了!
要求
仅在 Magento 2.4 下测试
安装
composer require wubinworks/module-webapi