【问题标题】:Getting values sent using post method in controller in magento 2 api在magento 2 api的控制器中使用post方法获取发送的值
【发布时间】:2016-11-26 16:13:30
【问题描述】:

我无法使用 http 请求获取从 post 方法发送的值。

我正在使用 get 方法获取值,但我需要使用 post 方法获取它。

我没有使用任何视图,我想调用 http url,并使用 post 方法在我的控制器中发送一些数据。

这就是我的控制器的样子,

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 的新手,我不明白问题出在哪里。 如果有人可以提供帮助,那就太好了。

【问题讨论】:

    标签: php api magento2


    【解决方案1】:

    这可能与http请求的Content-type有关,Magento只能理解Json和Xml(这是explained here)。如果您在请求中使用了不同的Content-type,或者您的数据与标头中声明的类型不匹配,则getPost() 将不起作用。

    作为后备,您始终可以使用以下方式获取所有 POST 数据:

    public function execute()
    {   
        $postData = file_get_contents("php://input");
    }
    

    请记住,这将获取原始字符串,因此您可能需要在使用它之前对其进行相应处理(例如使用 json_decode() 或类似的东西)。

    有关更多信息,请查看this SO question

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-11
      • 1970-01-01
      相关资源
      最近更新 更多