在 magento 2 api 的控制器中使用 post 方法获取发送的值
Getting values sent using post method in controller in magento 2 api
我无法使用 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 的新手,我不明白这是什么问题。
如果有人能提供帮助就太好了。
可能与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。
我无法使用 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 的新手,我不明白这是什么问题。 如果有人能提供帮助就太好了。
可能与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。