php - 在magento 2 api的 Controller 中使用post方法获取发送的值

标签 php api magento2

我无法使用 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/

相关文章:

rest - 如何在 rest API 后端获取产品列表及其详细信息是 magento2

permissions - 如果从浏览器调用 php exec 不执行

php - 我应该在 Ruby on Rails 中重写我的 Codeigniter/PHP 应用程序吗?为什么?

php - 如何使用 PHP 按字母顺序获取数据

python - Google Sheets API json 文件 - CLIENT_SECRET 和 oauth2client 凭据之间有什么区别?

Magento 2.2 : Child product of Configurable product missing attributes

javascript - 如何使用javascript连接到另一台服务器上的php

api - Google API token 端点 POST 返回错误请求 400

api - Google Charts Api - 单系列多色

Magento2 Composer 安装不起作用