4

I can not get values sent from post method, using http request.

I am getting values using get method, but I need to get it using post method.

I am not using any view, I want to call http url, and send some data in my controller using post method.

This is how my controller looks like,

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();
    }
}

I am new to magento 2, and I don't understand what is the problem. It will be great if someone can help.

u_mulder
  • 54,101
  • 5
  • 48
  • 64
Anand
  • 217
  • 2
  • 10

1 Answers1

3

It probably has to do with the Content-type of the http request, where Magento only understands Json and Xml (this is explained here). If you're using a different Content-type in the request or your data doesn't match the type declared in the header, then getPost() will not work.

As a fallback, you can always get all the POST data by using the following way:

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

Keep in mind that this will get the raw string, so you will likely need to process it accordingly before using it (for example with json_decode() or something like that).

For more information about this, check this SO question.

Community
  • 1
  • 1
peedee
  • 3,257
  • 3
  • 24
  • 42