我无法使用 http 请求获取从 post 方法发送的值。
我正在使用 get 方法获取值,但我需要使用 post 方法获取它。
我没有使用任何 View ,我想调用 http url,并使用 post 方法在我的 Controller 中发送一些数据。
这是我的 Controller 的样子,
namespace Spaarg\eMenuApi\Controller\Index;
class Products extends \Magento\Framework\App\Action\Action
{
public function __construct(\Magento\Framework\App\Action\Context $context)
{
return parent::__construct($context);
}
public function execute()
{
//$token = $this->getRequest()->getPostValue();
$token = $this->getRequest()->getPost();
}
}
我是 magento 2 的新手,我不明白问题出在哪里。 如果有人可以提供帮助,那就太好了。
最佳答案
这可能与 http 请求的 Content-type
有关,Magento 只理解 Json 和 Xml(这是 explained here )。如果您在请求中使用不同的 Content-type
或者您的数据与 header 中声明的类型不匹配,则 getPost()
将不起作用。
作为回退,您始终可以使用以下方式获取所有 POST 数据:
public function execute()
{
$postData = file_get_contents("php://input");
}
请记住,这将获取原始字符串,因此您可能需要在使用它之前对其进行相应的处理(例如使用 json_decode()
或类似的东西)。
有关此的更多信息,请查看 this SO question .
关于php - 在magento 2 api的 Controller 中使用post方法获取发送的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40820312/